Home: Perl Programming Help: Beginner:
creating a hash within a subroutine call?


Jun 19, 2013, 8:28 AM

Views: 991
creating a hash within a subroutine call?

Hi, I've been trying to search for how to do this but wasn't finding any answer.

Suppose I have a subroutine that takes as one of its params a reference to a hash

sub _my_sub {
my $hashRef = shift;
.... (do stuff with my hash reference)
return 0; (just an example)

now say I want to call this subroutine but I don't actually want to have to initialize a hash before doing it.

What I mean is, I don't want to have to do this:

my %ages = ("John", 43, "Paul", 25, "Marie", 22);
my $result = _my_sub(\%ages);

I want to be able to essentially make that hash on the fly, within the subroutine call. Meaning something like

my $result = _my_sub(\("John", 43, "Paul", 25, "Marie", 22));

(note: I know that syntax above is not correct. that's why I asked teh question because I"m not certain what WOULD be the correct syntax, or if this is even allowed in perl and if so, is it recommended, I wasn't sure if something weird would happen while doing this)

thanks so much!

(This post was edited by perlFun on Jun 19, 2013, 8:29 AM)

Veteran / Moderator

Jun 19, 2013, 8:48 AM

Views: 977
Re: [perlFun] creating a hash within a subroutine call?

use Data::Dumper; 

my $result = _my_sub( {John => 43, Paul => 25, Marie => 22} );
print $result;

sub _my_sub {
my $hashRef = shift;
print Dumper $hashRef;
return 0;

(This post was edited by FishMonger on Jun 19, 2013, 8:48 AM)