Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use "say" in Perl onelines without declaring 'use v5.11' or similar?

Tags:

perl

In newer Perls there is "say" command that behaves like println:

$ perl -e 'use v5.11; say "qqq"'
qqq

but it's a bit cumbersome to use in oneliners, as one needs to declare version...

$ perl -e 'say "qqq"'
String found where operator expected at -e line 1, near "say "qqq""

$ perl -e 'print "qqq\n"'
qqq # but \n is easy for forget and "print" is longer...

Is there a way to enable say without adding slashes (there can already by plenty of in the line) or moving cursor left to type use v5.11 in command line?

like image 653
Vi. Avatar asked Jul 02 '14 23:07

Vi.


2 Answers

If calling perl from the command line, you can use the -E flag

  • -E program: like -e, but enables all optional features

As demonstrated:

$ perl -E 'say "qqq"'
qqq
like image 113
Miller Avatar answered Sep 28 '22 00:09

Miller


As an option to -E, I use -l, which makes print work like say (add a newline). I use this most of the time myself, and I find that it completely replaces say.

$ perl -lwe'print "foo"'
foo

What it really does is set $\ to the current value of $/, which causes the oddity that the command line option -0 affects -l, which is something to look out for. The order of the switches matter, so that

$ perl -l -00 -e'print "hi"'

works as expected, but

$ perl -00 -l -e'print "hi"'

Does not (it sets $\ to "\n\n", for paragraph mode).

This latter case is practical when using paragraph mode, for re-printing the paragraphs easily. All in all, there are many benefits to using -l.

Technically, print is longer than say, but my fingers already type print automatically, and print is in the actual case shorter than print^H^H^H^H^Hsay.. (backspace that is)

like image 27
TLP Avatar answered Sep 27 '22 23:09

TLP