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:
and mine:for('a','anyone','cancel','declare','perlmonks'){$i=()=/e/g;print"$_: +$i\n"if(/a/);}
both print the identical output namely:/a/&&print"$_: ".y/e//.$/for'a','anyone','cancel','declare','perlmonks +'
but mine is 13 characters shorter.a: 0 anyone: 1 cancel: 1 declare: 2
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:
we can run:a anyone cancel declare perlmonks
to produce the same output.perl -lne"/a/&&print$_.': '.y/e//" t1.txt
Update: Just saw LanX -E switch update. For modern versions of perl, we can shorten to:
which should work everywhere. For Unix only, we can save another stroke or two by using -lnE'...' instead of -lnE"...".perl -lnE"/a/&&say$_.': '.y/e//" t1.txt
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Shorten this one-liner!
by lunix (Novice) on Aug 26, 2018 at 10:19 UTC |