Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: Shorten this one-liner!

by Marshall (Canon)
on Aug 25, 2018 at 23:28 UTC ( [id://1221107]=note: print w/replies, xml ) Need Help??


in reply to Shorten this one-liner!

I did not find your code particularly easy to understand.
An alternate coding could be like the following...
tr is a lot faster than using the regex engine.
#!/usr/bin/perl use warnings; use strict; my @words = ("anyone", "cancel", "declArE", "perlmonks", "pal"); # Note the "pal" case is an extra case that I added foreach my $word (@words) { if ($word =~ tr/aA//) # word contains an "A" or "a" { my $numE = $word =~ tr/eE//; print "$word $numE\n"; #number of e's in word with an "a" } } __END__ anyone 1 cancel 1 declArE 2 pal 0
I think shortening the code to a one-liner is a meaningless exercise.

Update: I don't see the reason to make a "one liner" other than to do it for the fun of doing it. This makes no difference in execution speed. White space and comments consume no MIPS and the difference in Perl compile speed is insignificant. This $words[$count] is very anti-Perl philosophy... subscripts are rare. Learn more Perl before trying to write a one-liner.

Another Update:
This will be about the same performance as the above code:

my @words = ("anyone", "cancel", "declArE", "perlmonks", "pal"); print "$_: ",tr/eE//, "\n" for grep{tr/aA//;}@words;
I asked a Python friend and here is one result:
words = ["anyone", "cancel", "declArE", "perlmonks", "pal"] print(*((word,word.upper().count('E')) for word in words if 'A' in wor +d.upper()))
I like my Perl code much better!

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1221107]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (5)
As of 2024-04-19 02:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found