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.