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

I have paired the problem down as much as possible. In the SSCCE below I am removing placeholder backticks between date and time (the reason for this lies in complete program). I am also removing extra spaces in the text (again, the reason for this lies in the complete program). When there is no extra space to remove the "$extra" variable contains the empty string, which I explicitly set to the empty string to recreate the error condition in the SSCCE.

The problem is the second and subsequent lines have the backtick removed (i.e., replaced with nothing), while the first line is processed as expected where the backtick is replaced by a single space.

It appears the substitution of "$extra" is taking out the backticks (for data lines 2 and following) before the following substitution replaces backticks with a single space. It's a mystery why only the first data line is processed correctly.

#!/usr/bin/perl use strict; use warnings; while ( <DATA> ) { chomp; my $fname = $_; print qq(\nBefore: $fname\n); my $extra = ''; $fname =~ s/$extra//; $fname =~ s/`/ /; print qq( After: $fname\n); } exit; __DATA__ 2025-05-05`09:22:00 7,674 -rw-rw-rw- C:\~Zipfile\H\Helpin +gHand\Software\DevTools\.edit.current 2025-05-05`09:22:00 7,674 -rw-rw-rw- C:\PerlApps\H\Helpin +gHand\Software\DevTools\.edit.current 2025-05-05`09:22:00 5,448 -rw-rw-rw- C:\~Zipfile\B\Bat\pi +cs\.edit.current

"It's not how hard you work, it's how much you get done."

Replies are listed 'Best First'.
Re: Strange Occurrence in Substitution Statement
by Corion (Patriarch) on May 06, 2025 at 18:54 UTC

    See Perlop on 'the empty pattern':

    If the PATTERN evaluates to the empty string, the last successfully matched regular expression in the current dynamic scope is used instead
      And a possible solution:
      $fname =~ s/(?:$extra)//;
      map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]
        Thank you for the possible solution Choroba! I tried it and it works. It looks like the non-capturing group prevents the last successfully matched regular expression from being used when the pattern is empty.

        "It's not how hard you work, it's how much you get done."

      Thank you for the reference and the explanation Corion!

      "It's not how hard you work, it's how much you get done."