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