Perl6 surprise: No reference operator

ChrisDolan on 2008-10-30T05:42:41

The most surprising change I've discovered so far in Perl6 is that the reference operator ('\') is no more. That is, the following code, while valid in both Perl5 and Perl6, behaves differently in each:

   my %hash;
   my $hashref = \%hash;


In Perl6 the \ operator creates Capture instances instead of references. To make Perl6 behave the way the above code does under Perl5 behavior (where a scalar "contains" the hash), do like this:

  my %hash;
  my $hashref = $(%hash); # itemization


Then to use that $hashref, do like this:

  my @keys = $hashref.keys;
  # Perl5 equivalent: 
  # my @keys = keys %{$hashref};
So, the $hashref feels less like a pointer and more like a container. The scalar delegates to its value, which is why the ".keys" works in this example without needing to explicitly dereference the scalar.

The funny thing is that Captures of Lists behave a lot like arrayrefs, so I didn't even notice I had misused the \ in the following code:

  my @array;
  my $arrayref = \@array;
  for @($arrayref) -> $val {
     say $val;
  }


The as-list operator, "@(...)", works about the same on Capture instances as it does on scalars that contain Lists -- in both cases, it returns a list of the enclosed values.