Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get an error when I try to use the reptition assignment operator with an array?

Tags:

perl

#!/usr/bin/perl

use strict;
use warnings;

my @a = qw/a b c/;
(@a) x= 3;
print join(", ", @a), "\n";

I would expect the code above to print "a, b, c, a, b, c, a, b, c\n", but instead it dies with the message:

Can't modify private array in repeat (x) at z.pl line 7, near "3;"

This seems odd because the X <op>= Y are documented as being equivalent to X = X <op> Y, and the following code works as I expect it to:

#!/usr/bin/perl

use strict;
use warnings;

my @a = qw/a b c/;
(@a) = (@a) x 3;
print join(", ", @a), "\n";

Is this a bug in Perl or am I misunderstanding what should happen here?

like image 820
Chas. Owens Avatar asked Sep 08 '09 16:09

Chas. Owens


1 Answers

My first thought was that it was a misunderstanding of some subtlety on Perl's part, namely that the parens around @a made it parse as an attempt to assign to a list. (The list itself, not normal list assignment.) That conclusion seems to be supported by perldiag:

Can't modify %s in %s

(F) You aren't allowed to assign to the item indicated, or otherwise try to change it, such as with an auto-increment.

Apparently that's not the case, though. If it were this should have the same error:

($x) x= 3;  # ok

More conclusively, this gives the same error:

@a x= 3;  # Can't modify private array in repeat...

Ergo, definitely a bug. File it.

like image 75
Michael Carman Avatar answered Sep 29 '22 15:09

Michael Carman