Re:Data munging in Perl 6 vs. Perl 5
by Mithaldu on Tuesday December 09, 2014 @03:17PM
(#8725399)
To be clear here, that Perl 5 code is not production grade code and i'd send anyone trying to commit that to a repo back to the hash mines.
[ Parent
| on HN ]
Could you elaborate a little? I ask because the Perl 5 code looks a lot like the Perl that I write. I'd like to improve, but the existing Perl code that I'm writing on top of is really bad. Like really, really bad. I don't have much quality Perl to compare against.
Two examples:
$freq{substr $grade{$_}, 0, 1}++ for keys %grade;
better: $freq{$_}++ for map { substr $_, 0, 1 } values %grade;
best: my @letters = map { substr $_, 0, 1 } values %grade;
$freq{$_}++ for @letters;
----------------------------and
open my $fh, '<:utf8', "grades.txt"
or die "Failed to open file: $!";
my %grade;
while (<$fh>) {
m/^(\w+) \s+ ([A-F][+-]?)$/x
or die "Can't parse line '$_'";
$grade{$1} = $2;
};
better: use 5.010;
use IO::All -binary, -utf8;
my $line_format = qr/
^ # line start
(?<student>\w+) # name
\s+ # gap
(?<grade>[A-F][+-]?) # grade
$ # line end
/x;
my $fh = io->file("grades.txt");
my %grade;
while (my $line = $io->getline) {
die "Can't parse line '$line'" if $line !~ $line_format;
$grade{$+{student}} = $+{grade};
}Very nicely done. I use Perl in my everyday job, and its nice to see that some people still know how to write good Perl.
You should have use strict; use warnings; then you would have noticed the my $fh and the $io->getline error
Dammit, you're right. I was working in a buffer without perl instrumentation enabled because i was composing a comment, not a script. Now i can't edit the comment anymore. :/
5.10 in production? Surely you're joking! 5.8 or bust.
Re:Data munging in Perl 6 vs. Perl 5
by peteretep on Wednesday December 10, 2014 @12:32AM
(#8727839)
Exactly. Perl's critics often completely overlook the degree to which liberal use of the map/reduce paradigm can simplify the graphical representation of your code and allow the powerful list processing features to be brought to bear. Consider:
use strict; use warnings; use List::Util
qw/reduce/;
map { print } join "\n", "Distribution of grades by letter:",
map { sprintf( "\t%s: %s student%s", @$_, $_ -> [1] == 1 ? '' : 's' ) }
map { my $c = $_ ; sort { $a -> [0] cmp $b -> [0] }
map { [ $_, $c->{$_} ] } keys %$c } reduce { $a->{chr(ord($b->[1]))}++; $a } {},
map { printf( "List of students with failing grades:\n\t%s\n", join ', ' ,
map { $_->[0] } grep {ord $_->[1] >68} @$_); @$_} reduce {push(@$a, $b); $a} [],
map { printf( "${^A}'s grade: %s\n" , $_ -> [1] ) if $_->[0] eq $^A; $_ }
map { $^A="Zsófia"; [split(/\s+/)] } <STDIN>
The use of strict and warnings making this particularly Modern Perl, you could almost be forgiven for thinking you were reading Haskell...