SPUG: deferencing a hash in an array of hashes
ced at carios2.ca.boeing.com
ced at carios2.ca.boeing.com
Mon Nov 6 18:40:36 CST 2000
> I have a subroutine which builds up an array of hashes in @attributes, and
> then I want to use one of those hashes as it's returned value.
> return $attributes[0]; # returns the hash reference in the array.
> How can I return the de-referenced hash? I seem to be having difficulty.
> Here's @attributes:
> DB<5> x @attribs
> 0 HASH(0x227a8d0)
> 'defaultvalue' => 'junkchar'
> 'initialization' => 'atconnection'
> ...
> I just figured I'll de-reference it into %hash and return it as a hash
> rather than a reference...
> my %hash = %{$attribs[0]}; # this must be wrong
> return %hash;
> Alas! This doesn't do what I want, now:
> DB<6> x %hash
> 0 'ishidden'
> 1 'false'
>...
> Can someone please show me the error of my ways?
> Ideally, I'd skip the "my %hash = " part altogether and just do something
> like
> return %{$attribs[0]}; # or whatever the proper syntax is.
You're fine. The return statement just unrolls the hash
and returns the list of key-value pairs.
So, e.g. in sub 'foo' simply:
return %{$attribs[0]};
then in the call that invokes 'foo':
my %return_hash = foo();
and that automagically populates your hash.
Note because a list is being returned, you could
have just as well created a simple array:
my @return_array = foo();
hope this helps,
--
Charles DeRykus
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
POST TO: spug-list at pm.org PROBLEMS: owner-spug-list at pm.org
Subscriptions; Email to majordomo at pm.org: ACTION LIST EMAIL
Replace ACTION by subscribe or unsubscribe, EMAIL by your Email-address
For daily traffic, use spug-list for LIST ; for weekly, spug-list-digest
Seattle Perl Users Group (SPUG) Home Page: http://www.halcyon.com/spug/
More information about the spug-list
mailing list