1

For the following piping in a Bash script :

Bash command | perl -ne 'single line perl command' | Another Bash command

The Perl command could only be single line. How about if I want to write more complex multi-line Perl commands. Could I use multiple "-e" options for each perl command line, such as :

perl -n -e 'command line 1' -e 'command line 2' -e 'command line 3'

Or could I use a "Here Document" for the multi-line Perl codes (the perl options, such as "-n", should still be able to be specified in such case.) ?

If "Here Document" could be used, could anyone illustrate how to use it with an example.

Thanks in advance for any suggestion.

2 Answers 2

6

If your Perl script is simply too long to be controllable on a single line (with semi-colons separating Perl statements), then bash is quite happy to extend your single quoted argument across as many lines as you need:

Bash-command |
perl -ne 'print something_here;
          do { something_else } while (0);
          generally("avoid single quotes in your Perl!");
          say q{Here is single-quoted content in Perl};
         ' |
Another-Bash-Command

Also the 'perldoc perlrun' manual says:

-e commandline

may be used to enter one line of program. If -e is given, Perl will not look for a filename in the argument list. Multiple -e commands may be given to build up a multi-line script. Make sure to use semicolons where you would in a normal program.

-E commandline

behaves just like -e, except that it implicitly enables all optional features (in the main compilation unit).

So you could also do:

Bash-command |
perl -n -e 'print something_here;' \
        -e 'do { something_else } while (0);' \
        -e 'generally("avoid single quotes in your Perl!");' \
        -e 'say q{Here is single-quoted content in Perl};' |
Another-Bash-Command

If the script gets bigger than, say, 20 lines (somewhere between 10 and 50, somewhat according to choice), then it is probably time to separate the Perl script into its own file and run that instead.

Sign up to request clarification or add additional context in comments.

Comments

4

For multiple lines of Perl, you simply need to separate the commands with semicolons rather than pass multiple -e calls. For example:

perl -n -e 'command line 1; command line 2;'

(though I wouldn't normally say a Perl block was a "command line", per se).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.