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

Matt Roper matt at mattrope.com
Thu Jun 24 14:58:33 PDT 2004


On Thu, Jun 24, 2004 at 02:46:39PM -0700, 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()?
> 
> 
> #!/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);

I believe you need to pass your hash by reference if you want to do
this.  The way you're calling the function above is basically the same
as doing:

    function("foo", "hello", "goodbye");
    
And then when you try to shift the hash off the stack, it tries to be
greedy and take 'goodbye' as another key to the hash.

I think what you need to do is pass the hash by reference, when you call
the function, i.e.

    function(\%hash, $scalar);

shift the hash off the parameter array as a reference (scalar):
       
       my ($hash, $scalar) = (shift, shift);

and dereference when actually doing the hash lookup:

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


Hope that helps.


Matt

-- 

*************************************************
* Matt Roper <matt at mattrope.com>                *
* http://www.mattrope.com                       *
* PGP Key: http://www.mattrope.com/mattrope.asc *
*************************************************


More information about the vox-tech mailing list