Re: How can pass hash to subroutine ?

[email protected] ("Jenda Krynicky")
Newsgroups perl.beginners
Message-ID <[email protected]>
From: "Jeff Peng" <[email protected]>
> On Fri, Jun 13, 2008 at 7:50 PM, sivasakthi <[email protected]> wrote:
> > Hi all,
> >
> > how can we pass hash to subroutine? and retrieving the hash in
> > subroutine to print values of hash.
> >
> 
> Hello,
> 
> Generally we use a reference.
> 
> my %hash = (1,2,3,4);
> mysub(\%hash);
> sub mysub {
>     my $hashref = shift;
>     print $hashref->{1};
> }
> 
> or you could pass hash directly to a subroutine,
> 
> mysub(%hash);
> sub mysub{
>     my %hash = @_;
>     print $hash{1};
> }

Except that in this case we do not pass a hash, but instead create a 
list of all keys and values in that hash and then use it to build a 
new hash inside the mysub{}. Which is safer (You can't accidentaly 
modify the passed hash), but if the hash is big it takes some time 
and some memory.

Jenda
===== [email protected] === http://Jenda.Krynicky.cz =====
When it comes to wine, women and song, wizards are allowed 
to get drunk and croon as much as they like.
	-- Terry Pratchett in Sourcery
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.