Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?

Re: perl: we package API -- oneliner

by bliako (Prior)
on Dec 14, 2018 at 10:24 UTC ( #1227248=note: print w/replies, xml ) Need Help??

in reply to perl: we package API -- oneliner

Trick #8: $ENV{}

    When you're writing a one-liner using -e in the shell, you generally want to quote it with ', so that dollar signs inside the one-liner aren't expanded by the shell. But that makes it annoying to use a ' inside your one-liner, since you can't escape a single quote inside of single quotes, in the shell.

    Let's suppose we wanted to print the username of anyone in /etc/passwd whose name included an apostrophe. One option would be to use a standard shell-quoting trick to include the ':

    perl -F: -lane 'print $F[0] if $F4 =~ /'"'"'/' /etc/passwd

    But counting apostrophes and backslashes gets old fast. A better option, in my opinion, is to use the environment to pass the regex into perl, which lets you dodge a layer of parsing entirely:

    env re="'" perl -F: -lane 'print $F[0] if $F4 =~ /$ENV{re}/' /etc/passwd

    We use the env command to place the regex in a variable called re, which we can then refer to from the perl script through the %ENV hash. This way is slightly longer, but I find the savings in counting backslashes or quotes to be worth it, especially if you need to end up embedding strings with more than a single metacharacter.


Replies are listed 'Best First'.
Re^2: perl: we package API -- oneliner
by haukex (Bishop) on Dec 14, 2018 at 13:10 UTC

    Or just use escapes, or if it's about passing something from the shell to Perl, the -s option...

    $ perl -sle 'print qq{\047\x27$x}' -- -x="'" ''' $ FOO='`´()/~?*+#"@$%&'"'"; perl -sle 'print $x' -- -x="$FOO" `´()/~?*+#"@$%&'

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1227248]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (8)
As of 2020-09-29 17:57 GMT
Find Nodes?
    Voting Booth?
    If at first I don’t succeed, I …

    Results (150 votes). Check out past polls.