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"
| [reply] |
You aren't aware of what the switches on your one-liner are doing for you. See perlrun
The -n is the most important one. It applies a while(<>) { ... } loop around your code. So, it is taking your input string, splitting it into lines, assigning each value in turn to $_, and then executing the body of your one-liner for each value. In a program, you have to specify that.
#!/usr/bin/perl
use strict;
use warnings;
use diagnostics;
my $A="abc\ndef\nghi\n";
my @list = split /\n/,$A;
while (<@list>) {
! /def/ and print
}
Updated: my most literal attempt didn't work, putting the split inside the while condition. So I use split to create an array. That works better.
| [reply] [d/l] |
</quote>You aren't aware of what the switches on your one-liner are doing for you. See perlrun
The -n is the most important one. It applies a while(<>) { ... } loop around your code. </quote>
You are correct. I am confused as all get out. I think what is getting me the worst is all the short hand and defaults. For instance, is "<>" short hand for "<STDIN>"?. What would really help me is if you would rewrite
echo -e "abc\ndef\nghi\n" | perl -wlne '! /def/ and print "$_";'
for me with "-we" in place of "-wple" with all the short hand and defaults removed so I could see exactly what is going on. (You would be my hero as I have asked this elsewhere and have not understood it there either. Mostly very helpful folks show me a better way to write it in a full script. And although greatly appreciated, it does not help me understand exactly what is happening in the "-wple" one liner or how to duplicate it in a full script.)
Many thanks, -T
| [reply] [d/l] |
use strict;
use warnings;
my $A = "abc\ndef\nghi\n";
while ($A =~ /(.+)/g)
{
print "$1\n" unless $1 =~ /def/;
}
Output:
13:59 >perl 1419_SoPW.pl
abc
ghi
14:00 >
Hope that helps,
| [reply] [d/l] [select] |
#!/usr/bin/perl
use strict;
use warnings;
use diagnostics;
my $B = "";
my $A = "abc
def
ghi
";
while ( $A =~ m{(.+)}g ) {
$B .= "$1\n" unless $1 =~ /def/;
}
print "\$B = \n$B\n";
$B = "";
while ( $A =~ m{(.+)}g ) {
$B .= "$1\n" while $1 =~ /def/;
}
print "\$B = \n$B\n";
$B =
abc
ghi
Use of uninitialized value $_ in pattern match (m//) at ./ExtractTest.pl line 21 (#1)
Now what am I doing wrong?
| [reply] [d/l] |
| [reply] |