Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

sending scalar and hash to function [SUMMARY]

2 views
Skip to first unread message

bu...@alejandro.ceballos.info

unread,
Jun 27, 2011, 2:44:54 PM6/27/11
to beginn...@perl.org

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.

sub dosomething
{
($myopt,$myparams) = @_;
%myparams = $myparams;
print "opt = $myopt\n";
while( my ($k, $v) = each %myparams )
{ print "$k = $v \n"; }
}


Mike Williams

unread,
Jun 27, 2011, 4:54:30 PM6/27/11
to bu...@alejandro.ceballos.info, beginn...@perl.org
On Mon, Jun 27, 2011 at 2:44 PM, <bu...@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

0 new messages