Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I best pass arguments to a Perl one-liner?

Tags:

I have a file, someFile, like this:

$cat someFile hdisk1 active hdisk2 active 

I use this shell script to check:

$cat a.sh #!/usr/bin/ksh for d in 1 2 do     grep -q "hdisk$d" someFile && echo "$d : ok" done 

I am trying to convert it to Perl:

$cat b.sh #!/usr/bin/ksh export d for d in 1 2 do     cat someFile | perl -lane 'BEGIN{$d=$ENV{'d'};} print "$d: OK" if /hdisk$d\s+/' done 

I export the variable d in the shell script and get the value using %ENV in Perl. Is there a better way of passing this value to the Perl one-liner?

like image 901
sfgroups Avatar asked Jul 23 '10 19:07

sfgroups


People also ask

How do you pass runtime arguments in Perl?

You can pass various arguments to a Perl subroutine like you do in any other programming language and they can be accessed inside the function using the special array @_. Thus the first argument to the function is in [0],thesecondisin_[1], and so on.

What is $# ARGV in Perl?

The variable $#ARGV is the subscript of the last element of the @ARGV array, and because the array is zero-based, the number of arguments given on the command line is $#ARGV + 1.


1 Answers

You can enable rudimentary command line argument with the "s" switch. A variable gets defined for each argument starting with a dash. The -- tells where your command line arguments start.

for d in 1 2 ; do    cat someFile | perl -slane ' print "$someParameter: OK" if /hdisk$someParameter\s+/' -- -someParameter=$d;  done 

See: perlrun

like image 194
Philippe A. Avatar answered Sep 20 '22 16:09

Philippe A.