Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

Re^2: Surprised by repetition (x) operator applied to a list

by Athanasius (Chancellor)
on Mar 30, 2014 at 03:55 UTC ( #1080265=note: print w/replies, xml ) Need Help??

in reply to Re: Surprised by repetition (x) operator applied to a list
in thread Surprised by repetition (x) operator applied to a list

One way to demonstrate the difference is to replace the expression [@list] with an equivalent subroutine call:

#! perl use strict; use warnings; use Data::Dumper; my @list = qw(abc def); my $nelts = 3; print "\nCase 1:\n"; my @array1 = (copy(\@list)) x $nelts; $array1[0][0] = 'xyz'; $array1[0][1] = '123'; print Dumper(\@array1); print "\nCase 2:\n"; my @array2 = map { copy(\@list) } 1 .. $nelts; $array2[0][0] = 'uvw'; $array2[0][1] = '456'; print Dumper(\@array2); sub copy { my ($list_ref) = @_; print "call copy($list_ref)\n"; my @clone = @$list_ref; return \@clone; }


13:51 >perl Case 1: call copy(ARRAY(0x1c7dec8)) $VAR1 = [ [ 'xyz', '123' ], $VAR1->[0], $VAR1->[0] ]; Case 2: call copy(ARRAY(0x1c7dec8)) call copy(ARRAY(0x1c7dec8)) call copy(ARRAY(0x1c7dec8)) $VAR1 = [ [ 'uvw', '456' ], [ 'abc', 'def' ], [ 'abc', 'def' ] ]; 13:51 >

— which confirms that with map the sub is called three times, but with x it is called only once.

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1080265]
[harishnv]: hey

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (6)
As of 2018-02-18 11:00 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (253 votes). Check out past polls.