It is not possible to pass a hash and a string of functions together in perl!

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

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

But the data seems to be mixed. Discarded data also includes $filename. here is the result.

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

This is how I called the subroutine.

coru_excel(%hash, "data_".$first."_".$last.".xls");
+3
source share
5 answers

Arguments are passed to routines as one undifferentiated list.

One solution is to reorder the arguments, so first a scalar.

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");
+9
source

You can pass the hash as a reference:

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

coru_excel(\%my_hash, $file);

Or you can give a special call to the final argument before initializing the hash:

sub coru_excel {
    my $filename = pop @_;
    my(%pushed_hash) = @_;
    print Dumper(%pushed_hash);
}
+6
source

:

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

:

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
}

perlreftut perlref .

Dumper , ( ).

+5

. Perl FAQ. :

perldoc -q pass

perldoc -q hash

perlfaq7: /return {Function, FileHandle, Array, Hash, Method, Regex}?

+3

, , , , .

#!/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;
}
+2

Source: https://habr.com/ru/post/1761534/


All Articles