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

Re: sending scalar and hash to function [SUMMARY]

Thread Previous
Mike Williams
June 27, 2011 13:54
Re: sending scalar and hash to function [SUMMARY]
Message ID:
On Mon, Jun 27, 2011 at 2:44 PM, <> 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,


Thread Previous Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About