Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

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

by dragonchild (Archbishop)
on Jul 29, 2009 at 02:42 UTC ( [id://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 (Abbot) 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?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (3)
As of 2024-04-20 14:56 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found