Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: Creating a copy of an array

by ichimunki (Priest)
on Dec 19, 2000 at 04:38 UTC ( [id://47296]=note: print w/replies, xml ) Need Help??


in reply to Creating a copy of an array

my @first = ( ['1','2','3'], ['11','22','33'] ); my @second = map { reref ( @$_ ) } @first; $first[0][2] = 4; print "$first[0][2]\n"; print "$second[0][2]\n"; sub reref { my @out = (); push (@out, $_) for @_; return \@out; }

This builds a new anonymous list reference for each list in the list. There is probably a better solution, but this works for your stated problem.

For the record, I have decided to purge the word array from my Perl vocabulary. Perl's lists have only the slightest relationship to arrays in other languages.

Replies are listed 'Best First'.
Re: Re: Creating a copy of an array
by repson (Chaplain) on Dec 19, 2000 at 06:37 UTC
    How about: my @second = map { [ @$_ ] ] @first; That expands each element then creates a new array ref from it. Without the slowdown of a subroutine call like you used.

    Still there are modules that can do this better.

    Hell you could do this (not recommended, there are modules made for copying).

    use Data::Dumper qw/Dumper/; my @first = ( ['1','2','3'], ['11','22','33'] ); my @second = @{ eval Dumper(\@first) };
      Cool. I think using turning the sub into an expression is much better. So how does any module beat a one liner? :)
        A one liner generally cannot take Everything into account. Since code may one day be reused in something else, something like my first snippet will work for the current problem but will be broken for others.

        My second snippet (with Data::Dumper) will work for most common problems of the copy type since it expands absolutely everything before recreating the structure. However using eval makes it likely to be slow, possibly insecure and less reliable.

        I suggest you have a good look at this article which provides a furthur in depth discussion of deep copying (which is what we are talking about here).

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://47296]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (7)
As of 2024-04-25 08:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found