in reply to advice for reading data from a file

Adding to other monks' comments, I can see two problems with your code:

1) while (<$fh>) { ...
This will break if the first line of the file is 0, the second line will not be read.

2) return $fields[2] =~ /.../;
What if the array @fields is empty? You will get warnings (assume you had 'use warnings' in your code, or haven't you?)

So I would suggest to add more error checking to the code to make it more robust.
sub check_field { my $file_name = shift; open my $fh, "<$file_name" or die "*** ERROR opening '$file_name': $!"; my @fields = (); while (defined (<$fh>)) { if ($. == 2) { chomp; @fields = split /;/; return 0 unless $#fields == 3; last; } } return 0 if $#fields < 0; return $fields[2] =~ /^\d+$/; }

Replies are listed 'Best First'.
Re: Re: advice for reading data from a file
by Anonymous Monk on Jan 19, 2004 at 00:39 UTC
    Hi Roger,

    i'm using 'warnings', but thanks for the 'defined' that i've missed :}

    but plz can you explain me why you are checking $#fields again in the line:

    return 0 if $#fields < 0;

    as it's already done in the loop (==3) ??

      That will guard against the case when your file has less than 2 lines, and the @fields only gets populated by the second line of the file.

        thanks for the explanation Roger,

        but concerning the 'defined' in the loop my code break breaks with this error:

        Use of uninitialized value in scalar chomp at /data/tmp/test_check_fie +ld.pl line 31, <$fh> line 2. <br><br> Use of uninitialized value in split at /data/tmp/test_check_field.pl l +ine 32, <$fh> line 2. <br> *** ERROR number of fields !=4
        after reading perldoc 'defined' :

        defined Returns a Boolean value telling whether EXPR has a value other than the undefined value "undef". If EXPR is not present, $_ will be checked.

        it seems to me that it's normal that my code break as it's not the value of the line that is returned but instead the boolean value of 'defined'..or am i wrong somewhere ?
Re: Re: advice for reading data from a file
by graff (Chancellor) on Jan 19, 2004 at 01:21 UTC
    1) while (<$fh>) { ...

    This will break if the first line of the file is 0, the second line will not be read.

    Hmm. Funny, it doesn't seem to behave that way for me, and I wouldn't expect it to. The magical while(<>) statement (with or without an explicit file handle) is actually shorthand for while( defined( $_ = <> ))

    Try it out with a file that has just "0\n" as the first line and anything after that on other lines -- I've tried it a number of ways, and the only way I could get it to stop at the first line was:

    while ( <> > 0) ...
    which is admittedly the sort of thing that very few people would do inadvertently.