Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: Putting text file into a hash

by binf-jw (Monk)
on Oct 17, 2008 at 09:04 UTC ( [id://717698]=note: print w/replies, xml ) Need Help??


in reply to Putting text file into a hash

Personally I write your code like this:
use English '-no_match_vars'; open $input_fh, '<', $input_fn or die 'Could not open file: ', $OS_ERR +OR; my $hash; while ( my $line = <$input_fh> ) { chomp $line; last if ! $line; # Split line with a limit of two my ( $word1 , $word2 ) = split /:/, $line, 2; $hash->{$word1} = $word2; } close $input_fh or die 'Could not close file: $OS_ERROR';

Alot of coding practices are personal preference but there are some good guidelines to follow.
I would say always use lexical variable for file handles. You can assign a lexical fh by opening as i've done or by using the glob from the symbol table like this:
my $output = *STDOUT;
Then you can even pass it via subroutines to assign handles:
## This in a package else where ## 'inside-out obj' sub assign_log_handle { my $self = shift; $log_handle->{$self} = shift; return; } ## From main code Your::Package->assign_log_handle( *STDERR );
Update: Just seen ikegami has already got there with this, But oh well. note: $OS_ERROR is the same as the $! that he mentioned.
Update: added: '-no_match_vars' :P John

Replies are listed 'Best First'.
Re^2: Putting text file into a hash
by linuxer (Curate) on Oct 18, 2008 at 14:21 UTC
      Yep use English '-no_match_vars' Have added it now.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (9)
As of 2024-03-28 10:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found