in reply to hash as subroutine argument

Well, yes it's possible to do it using something like your approach. Your file_merge() subroutine would look like this:

sub file_merge { my $hash_ref = shift; while (<>) { chomp; my ($key, @values) = split /-/, $_; push @{$hash_ref->{$key}}, [ @values ]; } }

But actually, that's not right as you're reading from the default filehandle each time.

I'd do this completely differently.

sub file_merge { my $filename = shift; open my $fh, '<', $filename or die "$filename: $!\n; my %hash; while (<$fh>) { chomp; my ($key, @values) = split /-/, $_; push @{$hash{$key}}, [ @values ]; } return %hash; }

You would then call it like this:

my %msisdn = file_merge('/tmp/subscription_list'); my %calls = file_merge('/tmp/Call_Det');

Another (perhaps better) alternative would be to return a hash reference rather than a hash.

As always strict and warnings will point out some of the major problems with your code.

--

See the Copyright notice on my home node.

Perl training courses

Replies are listed 'Best First'.
Re^2: hash as subroutine argument
by Anonymous Monk on Jul 03, 2009 at 04:29 UTC
    yeah this is much better option rather than passing hash as the argument. But the file hadle in the sub function has to be closed i suppose.
      But the file hadle in the sub function has to be closed i suppose.

      The filehandle is a lexical variable. It will be closed automatically as the variable goes out of scope (i.e. as the subroutine is exited).

      --

      See the Copyright notice on my home node.

      Perl training courses