tamaguchi has asked for the wisdom of the Perl Monks concerning the following question:

I guess some of you have seen this before...
I read something from an infile in common fashon like this:
while((my $line=<EXP>)=~/\S/) { chomp($line); (my ($k), my ($v))=split('=>', $line); $k=~s/\s//; $v=~s/\s//; $experimental_hash{$k}=$v; }
The problem is that if I dont have an empty row at the bottom of the infile I get the following error message: "Use of uninitialised value in pattern match (m//) at C:/bla/bla.." This doesn´t cause other trubbles more then that it is irritating. I frequently encounter this problem so I would be happy if you could give me an advice how to get rid of this problem. Thank you

Replies are listed 'Best First'.
Re: Error message while reading from file
by salva (Canon) on Feb 17, 2006 at 11:41 UTC
    the problem is that when the loop reachs the EOF, <EXP> returns undef. Rewrite the loop as:
    while(defined(my $line = <EXP>)) { next unless $line =~/\s/; ... }
Re: Error message while reading from file
by izut (Chaplain) on Feb 17, 2006 at 11:38 UTC
    Just modify your loop.
    foreach (<EXP>) { next unless m/\S/; ... }

    Igor 'izut' Sutton
    your code, your rules.

      Why switch from while to foreach?

      while (<EXP>) { next unless /\S/; ... }
      --
      <http://dave.org.uk>

      "The first rule of Perl club is you do not talk about Perl club."
      -- Chip Salzenberg

      generaly, this is not a good idea as it will read the full file in memory and if the file is too big you can run out of RAM.
Re: Error message while reading from file
by Aristotle (Chancellor) on Feb 20, 2006 at 00:30 UTC
    Everyone else gave you a bad transliteration of your loop. The proper rephrasing of that is
    while( my $line = <> ) { last unless $line =~ /\S/; # ... }

    That is, your loop does not merely skip lines which do not contain non-blanks, it actually terminates as soon as it encounters one.

    Makeshifts last the longest.