develooper Front page | perl.beginners.cgi | Postings from June 2011

Re: sending scalar and hash to function [SUMMARY]

Thread Previous
From:
Mike Williams
Date:
June 27, 2011 13:54
Subject:
Re: sending scalar and hash to function [SUMMARY]
Message ID:
BANLkTi=mbVLE6LsFy9gpGsG4i65U=Cy-uw@mail.gmail.com
On Mon, Jun 27, 2011 at 2:44 PM, <buzon@alejandro.ceballos.info> wrote:

>
> Found the solution (my apologies).
>
> I am receiving both an scalar, the second one as a reference, then it must
> be assigned to an other var.
>
> No.  It does not have to be assigned to another var.  Instead you should
dereference the reference.

 sub dosomething
>    {
>    ($myopt,$myparams) = @_;
>    ## %myparams = $myparams;    # skip the asssignment and creation oa a
> new hash
>    print "opt = $myopt\n";
>

       #### while( my ($k, $v) = each %myparams )
       while( my ($k, $v) = each %{$myparams} )   # dereference the
reference with %{$ref}

>      { print "$k = $v \n"; }
>    }
>
>
The assignment you had assigns the hash reference to a key of the hash you
created, with nothing assigned as a value.

It is a real, real bad idea (for many reasons) to create variables of
different types with the same names.

A major benefit of passing a reference is that you only move one item, the
reference, instead of the entire hash.  It doesn't make a lot of difference
in this case, but if you had a hash with thousands of key/value pairs
passing a reference and using that reference uses just a few bytes of
memory.  Copying the entire hash uses many thousands of bytes.

Happy hacking,

Mike

Thread Previous


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About