Perl line-mode oneliner with ARGV

I often need to run some single-line Perl for fast data management, like

some_command | perl -lne 'print if /abc/' 

Reading from the channel, I do not need a loop around the arg arg file name. How can I achieve the following?

 some_command | perl -lne 'print if /$ARGV[0]/' abc 

This gives an error:

 Can't open abc: No such file or directory. 

I understand what '-n' does

 while(<>) {.... } 

around my program, and <> accepts args as file names, but doing the following each time is a little impractical

 #/bin/sh while read line do some_command | perl -lne 'BEGIN{$val=shift @ARGV} print if /$val/' "$line" done 

Is there a better way to get the Perl ONE-LINER command line arguments β€œinside” without interpreting them as file names?

+4
source share
3 answers

Some solutions:

 perl -e'$p = shift; while (<>) { print if /$p/ }' pat perl -e'$p = shift; print grep /$p/, <>' pat # Inefficient. perl -ne'BEGIN { $p = shift } print if /$p/' pat PAT=pat perl -ne'print if /$ENV{PAT}/' 

Of course, it may make more sense to create a template that ORing or all the templates, rather than execute the same command for each template.

+2
source

Also short enough:

 ... | expr=abc perl -lne 'print if /$ENV{expr}/' 

Works in the bash , but maybe not in other shells.

+4
source

It depends on what you think will be in the lines you are reading, but you can play with:

 #/bin/sh while read line do some_command | perl -lne "print if /$line/" done 

It is clear that if $line can contain slashes, it will not fly. Then, AFAIK, you are stuck with the wording of the BEGIN block.

+2
source

Source: https://habr.com/ru/post/1480494/


All Articles