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
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.