Hash reference question

  • Thread starter Kristofer Pettijohn
  • Start date
K

Kristofer Pettijohn

I'm defining a hash similiar to what follows:

my $HASH = (
'key1' => (
'sub1' => 'key1value1',
'sub2' => 'key1value2'
),
'key2' => (
'sub1' => 'key2value1',
'sub2' => 'key2value2')
)

and I would like to pass the reference of $HASH{'key1'} to a sub. How
do I go about doing this?

Thanks!
 
C

ChrisO

Kristofer said:
I'm defining a hash similiar to what follows:

my $HASH = (
'key1' => (
'sub1' => 'key1value1',
'sub2' => 'key1value2'
),
'key2' => (
'sub1' => 'key2value1',
'sub2' => 'key2value2')
)

and I would like to pass the reference of $HASH{'key1'} to a sub. How
do I go about doing this?

First of all, define the hash properly using matching braces and not
parens and end with a semicolon:

my $hash = {
key1 => {
sub1 => 'key1value1',
sub2 => 'key1value2',
},
key2 => {
sub1 => 'key2value1',
sub2 => 'key2value2',
},
};

The quoting of the keys is not required unless you are going to include
whitespace in your key values.

To pass the key1 reference to a sub, just reference it:

subroutine( $hash->{key1} );
sub subroutine { print "$_[0]->{sub1}\n" }

-ceo
 
K

Kristofer Pettijohn

ChrisO said:
First of all, define the hash properly using matching braces and not
parens and end with a semicolon:

I do -- I guess I made the mistake of using parens instead of braces..
but the semicolons are definitely in the code -- I just typed up a short
un-tested example for my question.

Thanks for your help though - I understand it now.
 
U

Uri Guttman

SM> Ah.... that is not totally correct. When warnings are on and using
SM> strict, a key like this-is-a-key will *not* compile.

he should have said when using => you don't need to quote simple word
keys (a leading - is allowed because too many packages use -foo as
args). pretty much anything else needs normal quoting.

uri
 
C

ChrisO

Steve said:
Ah.... that is not totally correct. When warnings are on and using
strict, a key like this-is-a-key will *not* compile.

I'm not surprised. When I said "whitespace", I had some faint
recollection of dashes or underscores not working as you pointed out.
But since I never code without "use warnings qw( all );" and "use
strict;" I don't find much occasion to trip over those kinds of things.
I see these two pragmas pretty religiously recommended here in c.l.p.m
and for good reason.

-ceo
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top