Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: Extending Array

by moritz (Cardinal)
on Mar 21, 2012 at 14:57 UTC ( #960783=note: print w/ replies, xml ) Need Help??


in reply to Extending Array

$thing is a hash reference, not an array. See perldata and perlreftut for some more information.

Two ways to extend it:

$thing = { %$thing, 'C' => 'cutie', 'D' => 'pie' }; # OR $thing->{C} = 'cutie'; $thing->{D} = 'pie';

The first one generates a new hash and a new reference to it, the second adds items to the existing hash. Which one you should use depends on your use case (and is only relevant if there are other references to the same hash somewhere).


Comment on Re: Extending Array
Select or Download Code
Re^2: Extending Array
by sriharsha.sm (Initiate) on Mar 21, 2012 at 18:53 UTC

    Why do you want to create a new hash? Just adding to the old hash ref won't work?

    Can you give a scenario where do you use 1st case?

      Can you give a scenario where do you use 1st case?

      If I write a subroutine that receives a hash reference as an argument, I wouldn't modify it in-place, because the caller might want to re-use it.

      Simplified example:

      # caller: my %h = (a => 1, b => 2); something(\%h); say $_ for keys %h; # callee sub something { my $arg = shift; $arg = { %arg, c => 3, d => 4, }; # do more stuff with $arg here }

      If you use $arg->{c} = 3 in sub something, %h changes in the caller's code, which is very likely to cause confusion.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (10)
As of 2014-11-27 09:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My preferred Perl binaries come from:














    Results (183 votes), past polls