Howto print postmatch variable with perl one-liner?

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

I can print the postmatch variable with a perl script as follows:
#!/usr/bin/perl -w
$str = "abcdefghi"; $str =~ /def/; print "$`:$&:$'\n";

For perl one-liner, I can print without the $' as follows:
$ perl -e '$str = "abcdefghi"; $str =~ /def/; print "$`:$&:\n";'
But, I cannot print with $' as follows:
$ perl -e '$str = "abcdefghi"; $str =~ /def/; print "$`:$&:$'\n";'

Can you please let me know what I'm missing?
Thank you very much in advance!!!

Best Regards,

Re: Howto print postmatch variable with perl one-liner?

Quoted text here. Click to load it

You're falling foul of shell quoting. The shell interprets the ' in $'
as closing the single-quotes begun after -e, so then you get a big mess.

By far the easiest way around this is to use the /p flag introduced in
5.10. While this was implemented for efficiency reasons, all you really
care about is that it uses different variable names:

    perl -e'"abcdefghi" =~ /def/p;
        print "$:$:$\n";'

After that you're left with various forms of quoting. The cleanest is to
avoid $' altogether:

    perl -e'"abcdefghi" =~ /(.*?)def(.*)/; print "$1:$2:$3\n"'

(obviously with /s if you need it).

If that's too awkward you need to quote the ', either in shell or in
Perl. Quoting it in shell is a bit messy: shell doesn't honour '
inside single quotes, so you have to do it like this:

    perl -e'"abcdefghi" =~ /def/; print "$`:$&:$'''\n";'

Quoting it in Perl looks simpler but is actually more complicated: if
you write

    perl -e'"abcdefghi" =~ /def/; print "$`:$&:${chr 39}\n";'

it will work, but if you take away both $` and $& it will mysteriously
stop working. That's because perl doesn't bother to save values for
those three variables unless it saw them at compile-time (because it's
extremely expensive), and ${chr 39} is a symref which the compiler can't
see at compile time.


Re: Howto print postmatch variable with perl one-liner?

Quoted text here. Click to load it
Hello Ben,

Thank you very much for replying to my post. I do try all of your
great suggestions. And I note that there is a small typo in your
second suggestion:
$ perl -we'"abcdefghi" =~ /(.*?)def(.*)/; print "$1:$2:$3\n"'
Use of uninitialized value $3 in concatenation (.) or string at -e
line 1.
$ perl -we'"abcdefghi" =~ /(.*?)(def)(.*)/; print "$1:$2:$3\n"'
abc:def:ghi                     ^   ^
However, they are and they work like a charm.

I wish to thank you again for your valuable reply.

Best Regards,

Site Timeline