in reply to Shorten this one-liner!

To clarify that a word containing an 'a' but no 'e' should be printed, I've added an extra "a" word to your test data. Your program:

for('a','anyone','cancel','declare','perlmonks'){$i=()=/e/g;print"$_: +$i\n"if(/a/);}
and mine:
/a/&&print"$_: ".y/e//.$/for'a','anyone','cancel','declare','perlmonks +'
both print the identical output namely:
a: 0 anyone: 1 cancel: 1 declare: 2
but mine is 13 characters shorter.

For golf problems of this type I prefer to put the data not in code, but in a separate file read by the program from stdin. For example, for a data file t1.txt containing:

a anyone cancel declare perlmonks
we can run:
perl -lne"/a/&&print$_.': '.y/e//" t1.txt
to produce the same output.

Update: Just saw LanX -E switch update. For modern versions of perl, we can shorten to:

perl -lnE"/a/&&say$_.': '.y/e//" t1.txt
which should work everywhere. For Unix only, we can save another stroke or two by using -lnE'...' instead of -lnE"...".

Replies are listed 'Best First'.
Re^2: Shorten this one-liner!
by lunix (Novice) on Aug 26, 2018 at 10:19 UTC
    Hi, thanks for replying! Reading input from a file is a good idea, but I wanted to get a one-liner that can just be copy-pasted in itself and does the job, without having to type anything. See current shortest version in original post.