Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

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

by moritz (Cardinal)
on Jun 30, 2009 at 22:06 UTC ( #776196=note: print w/ replies, xml ) Need Help??


in reply to Golf: Improve this guy's fail . . . please!

This looks embarrassingly similar to my first Perl scripts, except that I never called subroutines with a leading & because I had the luck to learn Perl 5 from the start ;-).

It's a typical case of not knowing about autovivification: instead of assigning 0 to every possible hash key, and later sort out those which remained 0, you can simply leave out both steps altogether.

It is also typical in confusing ASCII with an 8-bit encoding.

A non-golfed version:

use strict; use warnings; use List::Util qw(sum); my %chars; local $/ = \1; while (<>) { $chars{$_}++ if /\w/; } my $total = sum values %chars; print "key\tcount\t%\n"; for (sort keys %chars) { printf "%s\t%d\t%.3f\n", $_, $chars{$_}, $chars{$_} / $total; }

It doesn't prompt for a filename, instead it either expects a file name on the command line, or reads from STDIN - in good old unix tradition.


Comment on Re: Golf: Improve this guy's fail . . . please!
Select or Download Code
Re^2: Golf: Improve this guy's fail . . . please!
by ikegami (Pope) on Jun 30, 2009 at 22:44 UTC

    At the opposite end of the spectrum, reading in the whole file:

    local $/; ++$chars{$_} for <> =~ /\w/g

    (Trimmed: local$/;++$c{$_}for<>=~/\w/g)

    It only accepts one file, though.

    Update: 5 shorter, accepts multiple files, and doesn't mess with $/:

    ++$chars{$_} for map /\w/g, <>

    (Trimmed: ++$c{$_}for map/\w/g,<>)

      I borrowed your idea and made something short and very ugly which does the whole job including percentages and total. I even added a count of distinct characters:
      ++$t,++$c{$_}for map/\w/g,<>; print$_,"\t",$c{$_},"\t",$c{$_}/$t*100,$/for sort keys %c; print"Distinct: ".keys(%c)."\tTotal: $t\n";

      I doubt I'd call that an "improvement", at least with a straight face. It could be cleaned up pretty easily, though.

        It could be cleaned up pretty easily, though.

        Then do it! No good leaving lousy code floating around... ;-)

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (12)
As of 2015-07-02 18:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (44 votes), past polls