in reply to Pattern matching and deriving the data between the "(double quotes) in HTML tag
Further to Athanasius's reply: NB: It's not quite right to say that the /g modifiers in the m//g matches are doing nothing. In fact, they're actively screwing you over (even if you get beyond the improper scoping of the lexical in the if-block).
Because the m//g matches are being called in scalar context in both cases in the OPed code, the /g modifier acts to leave the match position string pointer where it is after the first (successful) match, and to start matching from that position in the second match.
The first thing you search for in the string is 'startTime' followed by some stuff. Later, you search the same string for 'endTime' and some stuff, but you'll never find it because 'endTime' appears before 'startTime' and the regex engine (under the influence of the /g modifiers) has already passed by it in the string. This can be demonstrated by printing the pos match position of the string after the first match. (I've left out the chomp statements because I assume they really are useless.)
Removing either — or better yet, both! — of the confounding and potentially very confusing /g modifiers will get you what you want (if the lexical scoping problem is addressed too, of course).c:\@Work\Perl\monks>perl -wMstrict -le "my $timeLimit = 'xxx endTime=\"2016-12-28T23:59:59\" startTime=\"2016-09-30T00:00:0 +0\" yyy'; ;; $timeLimit =~ m/startTime=\"(.*?)\"/g; my $startTime = $1; print 'match position after 1st match: ', pos $timeLimit; ;; my $endTime; if ($timeLimit =~ m/endTime/) { $timeLimit =~ m/endTime=\"(.*?)\"/g; $endTime = $1; print 'match position after 2nd match: ', pos $timeLimit; } print \"[$startTime],[$endTime]\n\"; " match position after 1st match: 65 Use of uninitialized value in print at -e line 1. match position after 2nd match: Use of uninitialized value $endTime in concatenation (.) or string at +-e line 1. [2016-09-30T00:00:00],[]
Update: FWIW, my own preference in cases like this is to extract sub-strings from strings in list context and at the same time to generate an "extraction success" flag for possible later use:
c:\@Work\Perl\monks>perl -wMstrict -le "my $timeLimit = 'xxx endTime=\"2016-12-28T23:59:59\" startTime=\"2016-09-30T00:00:0 +0\" yyy'; ;; my $got_start = my ($start) = $timeLimit =~ m/startTime=\"(.*?)\"/; my $got_end = my ($end) = $timeLimit =~ m/endTime=\"(.*?)\"/; ;; print qq{start [$start], end [$end]} if $got_start and $got_end; " start [2016-09-30T00:00:00], end [2016-12-28T23:59:59]
Give a man a fish: <%-{-{-{-<
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Pattern matching and deriving the data between the "(double quotes) in HTML tag
by sp4rperl (Initiate) on Dec 06, 2016 at 03:45 UTC | |
by AnomalousMonk (Archbishop) on Dec 06, 2016 at 13:32 UTC |