Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

Re^5: Golf: Improve this guy's fail . . . please!

by dragonchild (Archbishop)
on Jul 29, 2009 at 02:42 UTC ( #784100=note: print w/replies, xml ) Need Help??

in reply to Re^4: Golf: Improve this guy's fail . . . please!
in thread Golf: Improve this guy's fail . . . please!

I was hoping you'd come by. Welcome to the Monastery.

This is 100x better. Well-done. Variable names can be improved, but I can actually scan this code and understand the basic intent. The biggest improvement now would be to skip intermediate variables that only exist once. So, something like:

use strict; use warnings FATAL => 'all'; use List::Utils qw( sum ); my $input = do { local $/; <>; }; my %letters; $letters{$_}++ for grep /\w/, split //, $input; my $total = sum values %letters; for ( sort keys %letters ) { printf "%s\t%d\t%.3f\n", $_, $letters{$_}, $letters{$_}/$total; } print "$total characters\n";
The big differences there are:
  • Removing intermediate variables
  • Scoping the localization of $/
  • Using a module to do the summation
  • Chaining functions in the grep split.
This would be considered more "perlish". Remember - readablity also includes conciseness. This is why well-written Java is less readable than well-written Perl.

My criteria for good software:
  1. Does it work?
  2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?

Replies are listed 'Best First'.
Re^6: Golf: Improve this guy's fail . . . please!
by jwkrahn (Monsignor) on Jul 29, 2009 at 02:52 UTC

    my %letters;
    $letters{$_}++ for grep /\w/, split //, $input;

    That would be simpler as:

    my %letters;
    $letters{$_}++ for $input =~ /\w/g;

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (3)
As of 2023-03-26 09:36 GMT
Find Nodes?
    Voting Booth?
    Which type of climate do you prefer to live in?

    Results (63 votes). Check out past polls.