Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical

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.

Replies are listed 'Best First'.
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?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://776196]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (11)
As of 2017-01-20 12:33 GMT
Find Nodes?
    Voting Booth?
    Do you watch meteor showers?

    Results (174 votes). Check out past polls.