Moritz Lenz wrote:
Hi Andy,

you seem to have discovered a whole bunch of bugs at once :/


Andy Colson wrote:
Hi List --

I'v started playing around with perl 6, and I am having problems with this example:

use v6;

sub xsum (@list)
{
         my $i = 0;
         print "summing: ";
         for @list
         {
                 $i += $_;
                 print $_,",";
         }
         say " = $i";
         return $i;
}
say "sum = ", xsum( (1,2,3,4,5) );

It returns this:

summing: 1 2 3 4 5, = -1.2289e+09
sum = -1.2289e+09


Looks like the "for @list" has one element in it, "1 2 3 4 5".

Not quite. When you add these lines:
    say @list.elems;
    say @list.WHAT
at the start of the sub, you'll get 5 as the answer for the count, which
seems correct, and 'List' as the type, which seems weird, but I'm not
sure if it's actually wrong (normally something that starts with an @
should be an Array, but since it's a subroutine argument it's read only.
So List might be fine).

The 'for' in conjunction with this weird List is broken. This works:
my @list = (1, 2, 3, 4, 5); my @x = @list; for @x { .say }
(prints all numbers on separate lines)
but this is broken:
sub a(@b) { for @b { .say } }; my @x = (1, 2, 3); a(@x)
prints all at once.

The second problem is the result of the += operation, which does
something really weird.
When you write it as $i = $i + 1, it gives you 5, which is the number of
items in the Array $i (which is correct, if we accept the previous bug
for the moment)

I'll write bug reports for both problems to [EMAIL PROTECTED]



The recommended way to write such a sub is

sub xsum([EMAIL PROTECTED]) { ... }
xsum(1, 2, 3);

With the * before the @list it is "slurpy", which means that it doesn't
expect one list as the argument, but rather an arbitrary number of items.
If you happen to have an Array already, you can interpolate it:
my @x = 1, 2, 3;
xsum(|@x);


HTH,
Moritz


Cool, thanks for the help there.

> The recommended way to write such a sub is
>
> sub xsum([EMAIL PROTECTED]) { ... }
> xsum(|@x);

Ahh, but, if I already had a list, would that flatten and then rebuild the list, correct? (and would, effectively, make a copy of the list?) (vs. just passing the list?) (just passing a list like that passes a reference, right? and wont make a new copy?)

Thanks,

-Andy

Reply via email to