The code works fine on Perl 5.12.1 does not work on 5.10.0

I wrote code (about 100 lines) that works fine on version 5.12.1. Unfortunately, my client uses version 5.10.0. So I tested the code on 5.10.0 and found that it does not work!

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


Edit:

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


Code that works since 5.12.1 but does not work on 5.10.0 ( $contents still remains an empty line after running the code)

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

Improved code that works in both versions.

 # read in the first 10 lines. my $contents = ''; my $i = 0; while (<FILE>) { last if $i >= 10; $contents .= $_; $i++; } 
+4
source share
2 answers

Take a look at the perldoc page. You will find the perdelta there. Or write your code and ask us to look at it;)

+4
source

There is an error in your first code example. Bare eof report status for last file read. On the first pass through the loop, you (presumably) have not read anything yet; not anything from FILE . It seems that the internal behavior of this invalid call has changed. In Perl 5.12.1, running perl -E "say eof" does not print anything. In Perl 5.10.0, it prints "1".

Explicit eof(FILE) testing eof(FILE) should fix the problem.

Tangent: your code is not very idiomatic. A higher approach would be

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

Idioms used:

  • Use a lexical file descriptor instead of the global type. ( $fh instead of FILE )
  • Use the range operator .. to track the number of rows read. This form implicitly checks the input line number $. .
  • Do not explicitly check for EOF (let the loop process it).
  • Use last to exit the loop earlier.
+9
source

Source: https://habr.com/ru/post/1315495/


All Articles