Search code examples
regexperl

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


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?


Solution

  • 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