2
#!perl6
use v6;

my $list = 'a' .. 'f';

sub my_function( $list ) {
    for ^$list.elems -> $e {
        $list[$e].say;
    }
}

my_function( $list );

First I tried this in perl5-style, but it didn't work:

for @$list -> $e {
    $e.say;
}
# Non-declarative sigil is missing its name at line ..., near "@$list -> "

How could I do this in perl6?

jjmerelo
  • 22,578
  • 8
  • 40
  • 86
sid_com
  • 24,137
  • 26
  • 96
  • 187
  • What exactly is it you want to do? The code in the first code block works fine on Rakudo HEAD at least. – arnsholt Feb 17 '11 at 16:42
  • The first block should be an explanation for what I want in the second block. – sid_com Feb 17 '11 at 18:48
  • @sid_com's perl5-style `for @$list -> $e { $e.say; }` syntax is fine. Rakudo just hadn't implemented it at the time. – raiph Nov 30 '14 at 16:58

3 Answers3

8

You don't dereference variables like this in Perl 6. Just use for $list

But that proably won't do what you want to do. 'a'..'f' doesn't construct a list in Perl 6, but rather a built-in data type called Range. You can check that with say $list.WHAT. To turn it into a list and iterate over each element, you'd use for $list.list

tadzik
  • 1,330
  • 1
  • 9
  • 12
4

Now, Rakudo 2015.02 works it ok.

You'd better use @ as twigil of variable name as array.

Perl 6 is context sensitive language, so if you want array act as 'true array', you'd better give it a suitable name.

#!perl6
use v6;

my @list = 'a' .. 'f';

for @list -> $e { $e.say };
4

These should work:

.say for @( $list );
.say for $list.list;
.say for $list.flat;

Since $listis a scalar, for $list will just iterate over a single item.

moritz
  • 12,710
  • 1
  • 41
  • 63