Insert a newline in a perl -e statement?

Consider the following Perl one-liner:

perl -e '$x; $y;'

I'm executing this command in bash and I'd like to insert a newline (\n) between the ; and $y. I'd like to know how to do this in two similar but slightly different ways:

  1. How can I insert the newline in that position by pressing some meta key sequence to insert the newline?

  2. How can I insert the newline in that position by typing some non-meta character sequence? (eg, '$x;\n$y;')

In both situations I want the Perl interpreter to see an actual newline, like this:

$x;
$y;

Solution 1:

Delete the space, then type CtrlV, CtrlJ.
Then Return.

The Ctrl-V prevents the shell interpreting the next character (newline) literally.

Solution 2:

The question you have asked only concerns how the shell interprets its input and passes it along to other programs. It has nothing to do with Perl, per se.

This answer addresses typing new input to the shell. Use the others' answer of ^V^J to insert a newline into an existing command line while using command-line editing.

You should just be able to put this in a script:

foo '$x;
$y;'

The argument given to the command will have a newline in the same place as it does in the script itself. You may need to take care to save such a script in such a way that uses Unix-style (LF-only) line breaks, otherwise you might get a CR+LF (DOS/Windows line breaks) or just CR (old Mac-style lineb reaks).

You can also do this at an interactive prompt, but you will see a continuation prompt before the second and any subsequent lines:

$ foo '$x;
> $y;'

In bash, you can also use the $'' quoting syntax to encode a newline character like this:

foo $'$x;\n$y;'

The argument passed to the program will be treated in a manner similar to an ANSI C string. If you want an actual backslash in the string you will have to escape it as \\, instead.

So, if you really want the literal-string quoting that single quotes give you, you should probably stick with an embedded newline so that you do not have to worry about extra escaping.