Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl CORE::say vs -E

Tags:

perl

In this answer is used the perl one-liner as:

perl -we '... CORE::say "x=$x"'

What is the advantage using the -e and CORE::say instead of the shorter: -E and plain say, e.g.:

perl -wE '... say "x=$x"'
like image 276
kobame Avatar asked Apr 28 '17 16:04

kobame


2 Answers

feature.pm was introduced to allow backwards-incompatible features to be added to Perl. -E enables all backward-incompatible features, which means a program that uses -E may break if you upgrade perl.

perl               -E'... say "foo";       ...'   # Forward-incompatible (5.10+)
perl -Mfeature=say -e'... say "foo";       ...'   # ok (5.10+)
perl -Mv5.10       -e'... say "foo";       ...'   # ok (5.10+)
perl -M5.010       -e'... say "foo";       ...'   # ok (5.10+)
perl               -e'... CORE::say "foo"; ...'   # ok (5.16+)

For example, say you wrote the following program in 2010:

perl -E'sub fc { my $acc=1; $acc*=$_ for 2..$_[0]; $acc } say fc(5);'

With the latest Perl in 2010 (5.12), the program outputs the following:

120

With the latest Perl in 2016 (5.24), the program outputs the following:

5

The difference is due to the addition of a feature to 5.16 that changes the meaning of that program when enabled. If one had avoided the use of -E, the program's behaviour would not have changed. Specifically, the following outputs 120 in 5.24:

perl -e'sub fc { my $acc=1; $acc*=$_ for 2..$_[0]; $acc } CORE::say fc(5);'
like image 166
ikegami Avatar answered Nov 16 '22 00:11

ikegami


You can see the difference like this:

C:\> perl -MO=Deparse -E "say"
use feature 'current_sub', 'evalbytes', 'fc', 'postderef_qq', 'say', 'state', 'switch', 'unicode_strings', 'unicode_eval';
say $_;

This is with perl 5.24.1 Now, without -E:

C:\> perl -MO=Deparse -e "CORE::say"
CORE::say $_;
-e syntax OK

The feature set included with -E will change in later versions (e.g. subroutine signatures) the wholesale inclusion of which may break existing programs. On the other hand, the latter will work with version 5.16 and later as @ikegami listed without other features clashing with programs written before their introduction.

like image 41
Sinan Ünür Avatar answered Nov 16 '22 02:11

Sinan Ünür