three18ti has asked for the wisdom of the Perl Monks concerning the following question:
Hello Monks
I had to bump the version in a number of files; as it was too many to do by hand I thought I could handle it in a oneliner.
Spoiler alert: I did get it worked out with a oneliner (at the end), but I'm flummoxed to no end as to why my first attempt was not working. Can anyone give me any clues to what I was doing wrong?
Here are my wrong initial attempts (and their output), the first one is probably the most puzzling, if $version is undef, where did "version '1.2.36'" come from?!?:
printf "foo\nversion '1.2.36'\nbaz\n" | perl -MData::Dumper -pi -e " +next unless /version/; ($version) = /version\s+('1\.2\.36')/; print $ +version" foo version '1.2.36' version '1.2.36' baz printf "foo\nversion '1.2.36'\nbaz\n" | perl -MData::Dumper -pi -e " +next unless /version/; ($version) = /version\s+('1\.2\.36')/; print D +umper $version" foo version '1.2.36' baz printf "foo\nversion '1.2.36'\nbaz\n" | perl -MData::Dumper -pi -e " +next unless /version/; ($version) = /version\s+('1\.2\.36')/; print D +umper \$version" foo $VAR1 = undef; version '1.2.36' baz printf "foo\nversion '1.2.36'\nbaz\n" | perl -pi -e 'next unless /ve +rsion/; ($version) = $_ =~ m{ version \s+ ''(1[.]2[.]36)'' }xms; prin +t "version:" . $version . "\n"' foo version: version '1.2.36' baz
Now of course, doing this in a script works:
$ cat wtf.pl #!/usr/bin/perl use 5.010; use strict; use warnings; while (<>) { next unless /version/; my ($version) = /version \s+ '(\d+[.]\d+[.]\d+)'/msx; say $version; } $ printf "foo\nversion '1.2.36'\nbaz\n" | perl wtf.pl 1.2.36
Epilogue: I did get it figured out, first of all, I only needed to change the last decimal point, so really I only needed to capture the last decimal point. I'm at a loss as to why this one works and my version was unable to match... (but I solved my problem so the issue is at least out of the way) (credit goes to my coworker)
printf "foo\nversion '1.2.36'\nbaz\n" | perl -pi -e 'if ($_ =~ m/ver +sion\s+.\d+[.]\d+[.](\d+)/) { my $v1 = quotemeta $1; my $v2 = $1 + 1; + $_ =~ s/$v1/$v2/ }' foo version '1.2.37' baz
I appreciate any insight that may help me avoid obvious mistakes in the future (although I've driven myself up a wall trying to find any "obvious" mistakes...)
Thanks!
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: [OneLiner] What am I doing wrong in my regex?
by Corion (Patriarch) on Jul 18, 2014 at 20:12 UTC | |
by perlfan (Parson) on Jul 18, 2014 at 20:17 UTC |