rgolwalkar
rgolwalkar

Reputation: 237

Array Operations in perl

Why does the code below return 11 with this :- @myarray = ("Rohan");

Explaination i got was :- The expression $scalar x $num_times, on the other hand, returns a string containing $num_times copies of $scalar concatenated together string-wise. So it should give 10 not 11 ...
code is as below :-

print "test:\n";
@myarray = ("Rohan"); # this returns 11
##@myarray = ("Rohan","G"); this returns 22
@myarray2 = (@myarray x 2);
@myarray3 = ((@myarray) x 2); #returns Rohan,Rohan and is correct

print join(",",@myarray2,"\n\n");
print join(",",@myarray3,"\n\n");

Upvotes: 0

Views: 572

Answers (2)

tchrist
tchrist

Reputation: 80384

What’s happening is that the x operator supplies scalar context not just to its right‐hand operand, but also to its left‐and operand as well — unless the LHO is surrounded by literal parens.

This rule is due to backwards compatibility with super‐ancient Perl code from back when Perl didn’t understand having a list as the LHO at all. This might be a v1 vs v2 thing, a v2 vs v3 thing, or maybe v3 vs v4. Can’t quite remember; it was a very long time ago, though. Ancient legacy.

Since an array of N elements in scalar context in N, so in your scenario that makes N == 1 and "1" x 2 eq "11".

Upvotes: 4

Eric Strom
Eric Strom

Reputation: 40142

Perl is doing exactly what you asked. In the first example, the array is in scalar context and returns its length. this is then concatenated with itself twice. In the second example, you have the array in list context and the x operator repeats the list.

Upvotes: 4

Related Questions