Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

code working fine on Perl 5.12.1 doesn't work on 5.10.0

Tags:

perl

I wrote some code (about 100 lines) that is working fine on version 5.12.1. Unfortunately my client is using version 5.10.0. So I tested the code on 5.10.0 and found it doesn't work!

Where can I find a list of differences between 5.10 and 5.12?


Edit:

I think the best answer to the question of "Where can I find a list of differences between 5.10 and 5.12" is plusplus' comment under the "accepted answer". For the explanation of the code below, please read Michael Carman's answer.


The code that works on 5.12.1 but does not work on 5.10.0 ($contents is still an empty string after running the code)

# read in the first 10 lines.
my $contents = '';
for (my $i = 0; $i < 10 && ! eof; $i++) {
    $contents .= <FILE>;
}

The improved code that works on both versions.

# read in the first 10 lines.
my $contents = '';
my $i = 0;
while (<FILE>) {
    last if $i >= 10;
    $contents .= $_;
    $i++;
} 
like image 548
powerboy Avatar asked Dec 12 '22 20:12

powerboy


2 Answers

There's a bug in your first code sample. A bare eof reports status for the last filehandle read. On of the first pass through the loop you (presumably) haven't read anything yet; not anything from FILE anyway. It appears that the internal behavior of this invalid call changed. Under Perl 5.12.1 running perl -E "say eof" prints nothing. Under Perl 5.10.0 it prints "1".

Explicitly testing eof(FILE) should fix the problem.

Tangent: Your code isn't very idiomatic. A more perlish approach would be

my $content;
while(<$fh>) {
    if ( 1 .. 10 ) { $content .= $_ }
    else           { last }
}

The idioms used are:

  • Use a lexical filehandle instead of a typeglob. ($fh instead of FILE)
  • Use the range operator .. to track the number of lines read. This form implicitly tests against the input line number $..
  • Don't explicitly test for EOF (let the loop handle it).
  • Use last to break out of the loop early.
like image 60
Michael Carman Avatar answered Jan 08 '23 18:01

Michael Carman


Look at the perldoc page. You''ll find the perldelta's there. Or post your code and have us look at it ;)

like image 26
Konerak Avatar answered Jan 08 '23 17:01

Konerak