tags:

views:

82

answers:

5

I am basically trying to pass a string and a hash to a subroutine in perl.

sub coru_excel {
    my(%pushed_hash, $filename) = @_;
    print Dumper(%pushed_hash);
}

But it seems data is getting mixed up. The dumped data also includes the $filename. here is the output.

...................
$VAR7 = 'Address';
$VAR8 = [
          '223 VIA DE
................
        ];
$VAR9 = 'data__a.xls'     <----- $filename
$VAR10 = undef;
$VAR11 = 'DBA';
$VAR12 = [
           'J & L iNC
..................
         ];

Here is how I called the subroutine.

coru_excel(%hash, "data_".$first."_".$last.".xls");
+8  A: 

Arguments are passed to subroutines as one undifferentiated list.

One solution is to reverse the order of the arguments so that the scalar is first.

sub coru_excel {
    my($filename, %pushed_hash) = @_;
}

coru_excel("FILE_NAME", %hash);

Another approach is to pass the hash by reference:

sub coru_excel {
    my($pushed_hash_ref, $filename) = @_;
}

coru_excel(\%hash, "FILE_NAME");
FM
+4  A: 

You have to pass the hash as a reference:

coru_excel(\%hash, "data_".$first."_".$last.".xls");

You use it like this:

sub coru_excel {
    my($pushed_hash_ref, $filename) = @_;
    my %pushed_hash = %{$pushed_hash_ref};

    print Dumper(%pushed_hash); # better: \%pushed_hash or $pushed_hash_ref
}

See perlreftut for a tutorial on references and perlref for further information.

Dumper also produces better usable information when you pass a hash (or array) reference.

musiKk
+6  A: 

You could pass the hash as a reference:

sub coru_excel {
    my($pushed_hashref, $filename) = @_;
    print Dumper(%$pushed_hashref);
}

coru_excel(\%my_hash, $file);

Or you could give special treatment to the final argument before you initialize the hash:

sub coru_excel {
    my $filename = pop @_;
    my(%pushed_hash) = @_;
    print Dumper(%pushed_hash);
}
mobrule
+2  A: 

A small program demonstrating how to do this using reference notation when passing the hash and shift in the subroutine to pull out the parameters.

#!/usr/bin/perl -w
use strict;
sub coru_excel(%$);
my %main_hash = ('key1' => 'val1', 'key2' => 'val2');
my $first = "ABC";
my $last = "xyz";
coru_excel(\%main_hash, "data_" . $first . "_" . $last . ".xls");
exit;

sub coru_excel(%$)
{
    my %passed_hash = %{(shift)};
    my $passed_string = shift;
    print "%passed_hash:\n";
    for my $k (keys %passed_hash) {
        print "  $k => $passed_hash{$k}\n";
    }
    print "\$passed_string = $passed_string\n";
    return;
}
GreenMatt
Is the function prototype serving any useful purpose in this example?
FM
@FM: Is it doing any harm?
GreenMatt
+3  A: 

See also the related Perl FAQ. From the command line:

perldoc -q pass

or

perldoc -q hash

Refer to perlfaq7: How can I pass/return a {Function, FileHandle, Array, Hash, Method, Regex}?

toolic