Hopefully this post is in Markdown.
You want to extract some capture groups in Perl. You are using strict
and warnings
. Some of the capture groups are optional, but if they aren’t there the others should still work. It feels like one regex, but you don’t want to see the warnings for the missing groups:
#!/usr/bin/perl -p use strict; use warnings; { no warnings 'uninitialized'; s/^(1+).*?(?:(2+) (3+))?$/$1 $2 $3/; }
Which gives:
$ echo "1foobar22 33" | ./test.pl 1 22 333 $ echo "111 baz" | ./test.pl 111
Instead of:
$ echo "1foobar22 333" | perl -p ./test.pl 1 2 333 $ echo "111 baz" | perl -p ./test.pl 111 baz
without the optional non-capturing group, or:
$ echo "1foobar22 333" | perl -p ./test.pl 1 22 333 $ echo "111 baz" | perl -p ./test.pl Use of uninitialized value $2 in concatenation (.) or string at ./test.pl line 7, <> line 1. Use of uninitialized value $3 in concatenation (.) or string at ./test.pl line 7, <> line 1. 111
with optionality but without the no warnings
block. I’m sure there’s a better way to do it, but I can’t remember. Incidentally, Perl is decent to input on iPhone but Posterous’s App is not; the Markdown failed and it uses accurate location without per-post choice.