Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl reports wrong line number if dying in multi line substitution. Is this expected or a bug?

Tags:

windows

perl

When I run the following code, the script dies with expected three at c:\temp\die.pl line 13..

use warnings;
use strict;

my $text = 'one two Three';

$text =~ s{

  (\w+)  # Find a word
  \s+
  (\w+)  # Find another word
  \s+
  (\w+)  # Find third word

}{

   # Insert a few lines on purpose
   # to make the point.

   die 'expected one'   unless $1 eq 'one';
   die 'expected two'   unless $2 eq 'two';
   die 'expected three' unless $3 eq 'three';

}ex;

I am somewhat surprised because the actual line that causes the death is line 21.

It seems that the interpreter does not count the pattern part of the substitution when it calculates(?) the line of death. Line 6 would be $text =~ s{ then the code until }{ is "skipped", making line 7 the following empty line, line 8 # Insert a few lines on purpose and so on until it reaches die 'expected three' unless $3 eq 'three'; having counted 13 lines.

Is this behaviour expected?

Is there a way to have perl print the real line of death?

perl -v starts with This is perl 5, version 18, subversion 1 (v5.18.1) built for MSWin32-x86-multi-thread-64int

Using carp instead of die

It was suggested I use carp instead of die.

It now dies (or carps) with the only slightly different expected three at c:\temp\die.pl line 14 which I attribute to the additional third line use Carp;.

like image 432
René Nyffenegger Avatar asked Mar 16 '16 08:03

René Nyffenegger


1 Answers

A quick bit of investigation showed this:

v5.10.1 dies on line 13.
v5.18.4 dies on line 13.
v5.20.2 dies on line 21.
v5.22.0 dies on line 21.

Then after checking the perldelta for 5.20, I found:

Line numbers inside multiline quote-like operators are now reported correctly. [perl #3643]

So, it seems the only way to get the right line number would be to upgrade to a later version of perl.

like image 186
Uncle Arnie Avatar answered Oct 31 '22 05:10

Uncle Arnie