[vox-tech] perl: function with hash and scalar args

Jeff Newmiller jdnewmil at dcn.davis.ca.us
Thu Jun 24 14:57:11 PDT 2004


On Thu, 24 Jun 2004, Peter Jay Salzman wrote:

> i have a function which takes a hash and scalar arg.  how is this done
> correctly?  why is $scalar undefined at the print statement in
> function()?

Because argument lists are always lists... and hashes decompose into lists
of alternating "key,value" pairs... and when you add $scalar into the
list, you can't differentiate where the hash portion of the list ends and
other arguments end.

> 
> #!/usr/bin/perl
> use strict;
> use diagnostics;
> 
> sub function(%$)
> {
>    my (%hash, $scalar) = (shift, shift);
> 
>    print "hash: $hash{foo}\n";
>    print "scalar: $scalar\n";
> }
> 
> my (%hash, $scalar);
> 
> $hash{foo} = "hello";
> $scalar    = "goodbye";
> 
> function(%hash, $scalar);

The usual solution is to pass references, which are always scalars:

------
#!/usr/bin/perl
use strict;
use diagnostics;

sub function( %$ )
{
   my ($hashref, $scalar) = (shift, shift);

   print "hash: $$hashref{foo}\n";
   print "scalar: $scalar\n";
}

my (%hash, $scalar);

$hash{foo} = "hello";
$scalar    = "goodbye";

function( \%hash, $scalar);
------

---------------------------------------------------------------------------
Jeff Newmiller                        The     .....       .....  Go Live...
DCN:<jdnewmil at dcn.davis.ca.us>        Basics: ##.#.       ##.#.  Live Go...
                                      Live:   OO#.. Dead: OO#..  Playing
Research Engineer (Solar/Batteries            O.O#.       #.O#.  with
/Software/Embedded Controllers)               .OO#.       .OO#.  rocks...2k
---------------------------------------------------------------------------



More information about the vox-tech mailing list