in reply to difference in regex
Hello ovedpo15,
In Perl, a function’s return value(s) may be different depending on the context in which the function is called. (Whether they are or not depends on the internal details of the function itself.) The statement my $value = $row =~ /.*,(.*)/; calls the regex operator m// in scalar context, so it returns true if the match succeeds and false if it fails. But in the statement my ($value) = $row =~ /.*,(.*)/; the parentheses around $value put the call to m// into list context and a list of the matches is returned.
By contrast, the substitution operator s/// returns the number of substitutions made regardless of the calling context. But you can change this behaviour by adding an /r modifier to the substitution. This creates a copy of the string (in this case $row), applies the substitutions (if any) to the copy, and returns that copy. E.g.
my $row = 'a,b,c,d,15'; my $str = $row =~ s/,[^,]*$//r; # $str now contains 'a,b,c,d'
See the sections m/PATTERN/msixpodualngc and s/PATTERN/REPLACEMENT/msixpodualngcer in perlop#Regexp-Quote-Like-Operators.
Hope that helps,
| Athanasius <°(((>< contra mundum | Iustus alius egestas vitae, eros Piratica, |
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: difference in regex
by ovedpo15 (Pilgrim) on May 29, 2018 at 13:58 UTC | |
by Eily (Monsignor) on May 29, 2018 at 14:11 UTC | |
by haukex (Archbishop) on May 29, 2018 at 14:20 UTC |