in reply to Regex returns match the first time. It returns everything thereafter
G'day guitarplayer68,
The base problem is that when /line/ matches, the range operator becomes TRUE; thereafter, it never becomes FALSE. See perlop: Range Operators for a full description of the flip-flop boolean states of this operator.
The more specific problem (i.e. why the operator doesn't become FALSE), would be that /\\Z/ never matches. What that matches is a literal backslash (\\) followed by a capital zed (Z). I suspect that's not what you meant. I further suspect that you're perhaps confused with \Z which matches the end of a string (possibly before a newline if one exists). See Assertions under perlre: Regular Expressions. Unfortunately, \Z is not what you want either.
From the data you've shown, there doesn't appear to be anything you can use to match the last line in each file. Given this, you might be better off changing your code to something with logic along these lines:
#!/usr/bin/env perl -l use strict; use warnings; my @test_data = ( [qw{discardA1 discardA2 lineA wantedA1 wantedA2}], [qw{discardB1 discardB2 lineB wantedB1 wantedB2}], [qw{discardC1 discardC2 lineC wantedC1 wantedC2}], ); for (@test_data) { my @ssh = @$_; my $wanted_found = 0; for my $line (@ssh) { if (! $wanted_found) { $wanted_found = $line =~ /line/; } else { print $line; } } }
Output:
wantedA1 wantedA2 wantedB1 wantedB2 wantedC1 wantedC2
If you also wanted the line that matched /line/, you can change that logic to this:
#!/usr/bin/env perl -l use strict; use warnings; my @test_data = ( [qw{discardA1 discardA2 lineA wantedA1 wantedA2}], [qw{discardB1 discardB2 lineB wantedB1 wantedB2}], [qw{discardC1 discardC2 lineC wantedC1 wantedC2}], ); for (@test_data) { my @ssh = @$_; my $wanted_found = 0; for my $line (@ssh) { if (! $wanted_found) { next unless $wanted_found = $line =~ /line/; } print $line; } }
Output:
lineA wantedA1 wantedA2 lineB wantedB1 wantedB2 lineC wantedC1 wantedC2
-- Ken
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Regex returns match the first time. It returns everything thereafter
by guitarplayer68 (Novice) on Nov 15, 2013 at 20:53 UTC | |
|
Re^2: Regex returns match the first time. It returns everything thereafter
by Laurent_R (Canon) on Nov 15, 2013 at 19:46 UTC |