Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: hash as subroutine argument

by davorg (Chancellor)
on Jul 02, 2009 at 13:16 UTC ( [id://776740]=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://776740]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (4)
As of 2024-04-23 19:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found