Perl6 / rakudo: problem with writing to loop variable

#!perl6
use v6;

my $longest = 3;
my @list = <a b c d e f>;

for @list -> $element is rw {
    $element = sprintf "%*.*s", $longest, $longest, $element;
    $element.say;
}

It works. But in the second and third I get an error message. How can I make them work?

#!perl6
use v6;

my $longest = 3;
my @list = <a b c d e f>;

for @list <-> $element {
    $element = sprintf "%*.*s", $longest, $longest, $element;
    $element.say;
}

# ===SORRY!===
# Missing block at line 11, near ""

.

#!perl6
use v6;

my $longest = 3;
my $list = <a b c d e f>;

for $list.list -> $element is rw {
    $element = sprintf "%*.*s", $longest, $longest, $element;
    $element.say;
}

# Cannot modify readonly value
#   in '&infix:<=>' at line 1
#   in <anon> at line 8:./perl5.pl
#   in main program body at line 1
+3
source share
1 answer

Regarding your second example

It may <->not have worked in Rakudo Perl, but has been fixed in later versions. (This is due to the deep parsing issue that required a better long token matching algorithm than at the time.)

Regarding your third example

Statement

my $list = <a b c d e f>;

creates $listas a data type Seq, and elements Seqare considered immutable. Do you really want to $listbecome Arraylike in:

my $list = [<a b c d e f>];

, :

pmichaud@orange:~/rakudo$ cat x.p6
#!perl6
use v6;

my $longest = 3;
my $list = [<a b c d e f>];

for $list.list -> $element is rw {
    $element = sprintf "%*.*s", $longest, $longest, $element;
    $element.say;
}

pmichaud@orange:~/rakudo$ ./perl6 x.p6
  a
  b
  c
  d
  e
  f
pmichaud@orange:~/rakudo$ 

, !

+6

Source: https://habr.com/ru/post/1793053/


All Articles