CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Syntax to de-reference keys %hash, inline?

 



perlFun
Novice

Jul 21, 2014, 1:43 PM

Post #1 of 4 (231 views)
Syntax to de-reference keys %hash, inline? Can't Post

This is a pretty basic question but I can't seem to figure it out.

I have a hash:


Code
my %hash = (key1 => val1, key2 => val2, ... , keyN => valN);

I need call a subroutine, and pass as a named param an arrayref storing the keys of this hash. I know I have 'keys %hash' at my disposal, but this returns an actual array, and I'm not sure how to dereference it inline. If I do:


Code
&my_sub(named_param=>\keys %hash);


this doesn't work.

Is my only option to do:


Code
my @keys = keys %hash; 
&my_sub(named_param=>\@keys);

? I don't mind the extra line of code, I'm just curious if there's a way to do this inline


(This post was edited by perlFun on Jul 21, 2014, 1:49 PM)


FishMonger
Veteran / Moderator

Jul 21, 2014, 3:18 PM

Post #2 of 4 (212 views)
Re: [perlFun] Syntax to de-reference keys %hash, inline? [In reply to] Can't Post


Code
my_sub( { named_param => [keys %hash] } );



(This post was edited by FishMonger on Jul 21, 2014, 3:20 PM)


perlFun
Novice

Jul 21, 2014, 3:21 PM

Post #3 of 4 (209 views)
Re: [FishMonger] Syntax to de-reference keys %hash, inline? [In reply to] Can't Post

Just out of curiosity, why doesn't this end up putting the array (keys %hash) within an arrayref? I would think from the syntax I'd end up with this data structure:

[(key1,key2,...,keyN)]

rather than

[key1,key2,...,keyN]


FishMonger
Veteran / Moderator

Jul 21, 2014, 4:05 PM

Post #4 of 4 (202 views)
Re: [perlFun] Syntax to de-reference keys %hash, inline? [In reply to] Can't Post

Does this help?

Code
use strict; 
use warnings;
use Data::Dumper;

my %hash = (key1 => 'val1', key2 => 'val2', keyN => 'valN');

my_sub( named_param => \keys %hash );
my_sub( named_param => [keys %hash] );
my_sub( {named_param => [keys %hash]} );

sub my_sub {
print Dumper \@_;
}


Output:

Code
$VAR1 = [ 
'named_param',
\'key2',
\'key1',
\'keyN'
];
$VAR1 = [
'named_param',
[
'key2',
'key1',
'keyN'
]
];
$VAR1 = [
{
'named_param' => [
'key2',
'key1',
'keyN'
]
}
];


 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives