lunix has asked for the wisdom of the Perl Monks concerning the following question:
Hi all
The task is the following: We have an array of words for example ["anyone", "cancel", "declare", "perlmonks"]. We need to print the word, if it contains an "a" and also the number of "e"-s in that word. The syntax has to be: "word: number". Easy, right? Here is a perl program that does this and is very easy to understand:
This outputs:
Just for fun, I am searching for the shortest perl one-liner that does the same. This is the shortest version I could come up with, with my current knowledge of perl:
I was wondering what kind of magic solution the great minds here could come up with. Feel free to impress me! :)
Update: Current shortest version is
perl -E'/a/&&say"$_: ".y/e//for anyone,cancel,declare,perlmonks'
The task is the following: We have an array of words for example ["anyone", "cancel", "declare", "perlmonks"]. We need to print the word, if it contains an "a" and also the number of "e"-s in that word. The syntax has to be: "word: number". Easy, right? Here is a perl program that does this and is very easy to understand:
#!/usr/bin/perl -w use strict; my @words = ("anyone", "cancel", "declare", "perlmonks"); my $count = 0; foreach (@words) { if ($words[$count] =~ m/a/i) { my $number = () = $words[$count] =~ /e/gi; print "$words[$count]: $number\n"; } $count ++; }
This outputs:
anyone: 1 cancel: 1 declare: 2
Just for fun, I am searching for the shortest perl one-liner that does the same. This is the shortest version I could come up with, with my current knowledge of perl:
perl -e 'for('anyone','cancel','declare','perlmonks'){$i=()=/e/g;print +"$_: $i\n"if(/a/);}'
I was wondering what kind of magic solution the great minds here could come up with. Feel free to impress me! :)
Update: Current shortest version is
perl -E'/a/&&say"$_: ".y/e//for anyone,cancel,declare,perlmonks'
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Shorten this one-liner!
by LanX (Saint) on Aug 25, 2018 at 21:56 UTC | |
by lunix (Novice) on Aug 26, 2018 at 10:03 UTC | |
Re: Shorten this one-liner!
by eyepopslikeamosquito (Archbishop) on Aug 26, 2018 at 07:00 UTC | |
by lunix (Novice) on Aug 26, 2018 at 10:19 UTC | |
Re: Shorten this one-liner!
by eyepopslikeamosquito (Archbishop) on Aug 26, 2018 at 12:22 UTC | |
by lunix (Novice) on Aug 26, 2018 at 15:22 UTC | |
by Marshall (Canon) on Aug 28, 2018 at 00:51 UTC | |
Re: Shorten this one-liner!
by Marshall (Canon) on Aug 25, 2018 at 23:28 UTC |
Back to
Seekers of Perl Wisdom