26 ms·
Two examples: $freq{substr $grade{$_}, 0, 1}++ for keys %grade; better: $freq{$_}++ for map { substr $_, 0, 1 } values %grade; best: my @letter
by Mithaldu 12y ago
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};
}
- hvs 12y agoVery nicely done. I use Perl in my everyday job, and its nice to see that some people still know how to write good Perl.
- Ultimatt 12y ago5.10 in production? Surely you're joking! 5.8 or bust.
- pjfl 12y agoYou should have use strict; use warnings; then you would have noticed the my $fh and the $io->getline error
- Mithaldu 12y agoDammit, 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. :/