Remix.run Logo
zahlman 4 hours ago

I remember trying to use the new "reference" feature (when it was new), with "blessing" and so on and so forth, to try to create real data structures, and finding in some way or another that it was just not regular. I can't recall the details, but something along the lines of a feeling that the syntax worked differently for, say, the top level of a tree (or first index of a multidimensional array, etc.) vs the rest of the structure.

darrenf 3 hours ago | parent [-]

In the main, the sigil refers to the type of the eventual value, regardless of what contains it. The tl;dr is that you mostly use `$` unless you're wanting more than one value, or to dereference (when you use the sigil for the type of reference). Some examples:

    @array = ("a", "b", "c", "d"); # @array contains scalars
    $array[0];                     # use `$` for a single element
    @array[0..2];                  # use `@` for an array slice
    @array = ( [1..5], [6..10] );  # @array now contains array references
    $array[0];                     # use `$` still because references are scalars
    $array[0][1];                  # still use `$` even when going multidimensional
    @{ $array[0] };                # use `@` to dereference an array ref to array
    %hash = ( a => "b", c => "d"); # % for hash of key/value pairs
    $hash{a};                      # `$` because you're getting a single scalar
    @hash{"a","c"};                # `@` because you're getting an array of values
Where things become a bit less regular is the difference between reference and non-reference for hashes and arrays when they are top level. At the top level, you need a `->` but that becomes optional at levels below (because at levels below, they have to be references).

    $arrayref = [1,1,2,3,5];       # `$` because we're creating an array reference
    $arrayref->[0];                # `->` because top level
    $arrayref = [ [ 1 ], [ 2 ] ];  # arrayref of arrayrefs
    $arrayref->[0][0];             # no second `->`
    $arrayref->[0]->[0];           # ... but you can use it if you want!
And then there's stuff like getting a slice out of an arrayref

    $arrayref = [1,1,2,3,5];
    $arrayref->@[0..3]; # oh dear. get a real array with an `@` but not at the start!
So... yeah.
zahlman 2 hours ago | parent [-]

> Where things become a bit less regular is the difference between reference and non-reference for hashes and arrays when they are top level. At the top level, you need a `->` but that becomes optional at levels below

Yes, that's probably what I was remembering. Thanks for the exposition.