Pass scalar and hash to subroutine in Perl

Viewed 156

I have written a script which passes a scalar and hash data into an subroutine.

While passing an hash I was passing an reference and inside the subroutine dereferencing it while iterating (using foreach loop).

#!/usr/bin/perl
use strict; use warnings;
use Data::Dumper;

my %hash = (
                '1' => [ 'A', 'B', 'Z', 'A' ],
                '2' => [ 'C', 'D' ],
                '3' => [ 'E', 'E' ]
);

my $keyword = "my_test_keyword";
print_data($keyword, \%hash);
print "End of the Program\n";

sub uniq (@) {
    my %seen;
    my $undef;
    my @uniq = grep defined($_) ? !$seen{$_}++ : !$undef++, @_;
    @uniq;
}

sub print_data {
    my ($kw, $h) = @_;
    print "Keyword:$kw\n"; #my_test_keyword should be printed
    
    foreach my $key (sort keys %$h) {
        print "Key:$key\n";
        print "Value(s):", join('#', uniq @{%$h{$key}}), "\n";
    }
    return;
}

Is it a good approach or do I need to pass hash as it is (without reference) and retrieve in subroutine.

1 Answers

You can't pass hashes (or arrays) to subs, only zero or more scalars. Using

f(%hash)

results in

f($key1, $hash{$key1}, $key2, $hash{$key2}, ...)

So you would have to recreate the hash on the inside. Passing a reference is a common and much cheaper alternative.

Related