Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: adding elements to already exisiting elements in an array

by regexes (Hermit)
on May 15, 2008 at 07:14 UTC ( [id://686673]=note: print w/replies, xml ) Need Help??


in reply to adding elements to already exisiting elements in an array

Hello,

In addition to samtregar's comments below, if you know that you will have multiple entries, then you need to initialize the array as an array reference to begin with... for example,


Note: code has not been tested.

if ( ref( $Elements[$1] ) eq "ARRAY" ) { push ( @{$Elements[$l]} }, $value ); } else { $Elements[$1] = [$value]; }
See perldoc -f ref for some details...

Hope this helps!

regexes


-------------------------
Nothing in the world can take the place of persistence. Talent will not; nothing is more common than unsuccessful men with talent. Genius will not; unrewarded genius is almost a proverb. Education will not; the world is full of educated derelicts. Persistence and determination are omnipotent. The slogan "press on" has solved and always will solve the problems of the human race.
-- Calvin Coolidge, 30th President of the USA.

Replies are listed 'Best First'.
Re^2: adding elements to already exisiting elements in an array
by johngg (Canon) on May 15, 2008 at 10:17 UTC
    if ( ref( $Elements[$1] ) eq "ARRAY" ) { push ( @{$Elements[$l]} }, $value ); } else { $Elements[$1] = [$value]; }

    Note that you do not need to test whether you already have an array ref. as Perl will auto-vivify an anonymous array for you.

    $ perl -MData::Dumper -e' > @arr = (1, 2); > push @{ $arr[2] }, 3, 4; > push @arr, 5; > print Data::Dumper->Dump([\ @arr], [q{*arr}]);' @arr = ( 1, 2, [ 3, 4 ], 5 ); $

    Note also that samtregar's comments are above yours, you may have your monitor upside down :-)

    Cheers,

    JohnGG

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (5)
As of 2024-04-19 22:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found