Maintainability notes:
- Include the name of the file in the error message. Just knowing that you failed because , "No such file or directory" is not nearly as useful as knowing which file purportedly does not exist.
- Why put the lines into an array? It is just as easy to read from the file directly, and that gives you the option of reading it incrementally with a while loop. (Huge improvement on large files.)
- Indentation?
- You forgot to chomp the lines from the file.
- I find that using a hash slice rather than a list of variables is much more maintainable. That way minor (or major) data format changes are much easier to handle.
With those changes this example would become something like:
#! perl
use strict;
my $file = shift(@ARGV) || "foo.txt";
open(FH, $file) or die("Cannot read '$file': $!");
my @field_list = qw(put in reasonable names here for your data);
while (<FH>) {
chomp;
my %row;
@row{@field_list} = split /\|/, $_;
my ($field_data, $comment) = split /;/, $row{data};
print "$field_data\n";
}
Of course the original author should switch to a data format which is self-documenting (for instance make the first line a header line that says what fields are in use). And when you do that, the use of a hash slice makes things very easy - just read the list of field names out of the header line!
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.