in reply to Regex match on implicit default variable ($_) in a script, not a one liner

I want to remove the middle line from $A. Same as I did with the one liner.
What is desired:
Before: $A="abc\ndef\nghi\n"
After: $B="abc\nghi\n"

Heres another way, which you can also iterate through the array easily (once you have built one ofcourse) :)

use strict; use warnings; my @array = "abc\ndef\nghi\n"; print $1 . $3 if $array[0] =~ /(.*)(\ndef)(.*)/s;
  • Comment on Re: Regex match on implicit default variable ($_) in a script, not a one liner
  • Download Code

Replies are listed 'Best First'.
Re^2: Regex match on implicit default variable ($_) in a script, not a one liner
by Laurent_R (Canon) on Oct 24, 2015 at 18:43 UTC
    I do not see your point about using an array here, since you are not really using an array but just one element of your array, so that a scalar value would just work the same way:
    my $scalar = "abc\ndef\nghi\n"; print $1 . $3 if $scalar =~ /(.*)(\ndef)(.*)/s;

      I was trying to duplicate what the one liner does, so I wanted to keep it as a string.
      I finally figured it out: preserve $1 and use "if" instead of "while":

      #!/usr/bin/perl # full script the following one liner: # $ echo -e "abc\ndef\nghi\n" | perl -wlne '! /def/ and print "$_";' # abc # ghi use strict; use warnings; use diagnostics; my $C; my $B = ""; my $A = "abcdef fhijkl mnopqr "; while ( $A =~ m{(.+)}g ) { $B .= "$1\n" unless $1 =~ /ijk/; # $B .= "$1\n" unless $1 =~ /xyz/; } print "\$B = \n$B\n"; $B = ""; while ( $A =~ m{(.+)}g ) { $C = $1; $B .= "$C\n" if $C =~ /ijk/; } print "\n\$B = \n$B\n";

      $B =
      abcdef
      mnopqr


      $B =
      fhijkl

      Thank you for all the help! -T