B
bill
There are a couple of situations that I encounter frequently, and
I wonder if there are established Perl idioms for dealing with them.
1. The problem is to read and discard lines from a file until a
condition is met (usually some regexp match), and then process
subsequent lines. E.g.
my $found;
while (<IN>) {
if (meets_condition($_)) {
$found = 1;
last;
}
}
die "Bad data\n" unless $found;
while (<IN>) {
# etc.
}
2. Finding the first position at which two strings differ.
sub first_different {
my $len = (sort map length, @_[0, 1])[-1];
my $n;
for (my $i = 0; $i < $len; ++$i) {
if (substr($_[0], $i, 1) ne substr($_[1], $i, 1)) {
$n = $i;
last;
}
}
return defined $n ? $n : -1;
}
Are there nice Perl idioms for either of these two tasks?
-bill
P.S. This is not golf, now! I'm *sure* that it is possible to use
some insanely arcane Perl constructs to make the above a *lot* more
succinct, but the results probably would not qualify as "idioms"
in my book. Idioms are pithy, but not terribly obscure. They
don't leave you scratching your head after several minutes of trying
to decrypt them. (I'd say that
select((select(FH), $|=1)[0]);
is the most obscure construct that I'd still be willing to call an
"idiom".)
I wonder if there are established Perl idioms for dealing with them.
1. The problem is to read and discard lines from a file until a
condition is met (usually some regexp match), and then process
subsequent lines. E.g.
my $found;
while (<IN>) {
if (meets_condition($_)) {
$found = 1;
last;
}
}
die "Bad data\n" unless $found;
while (<IN>) {
# etc.
}
2. Finding the first position at which two strings differ.
sub first_different {
my $len = (sort map length, @_[0, 1])[-1];
my $n;
for (my $i = 0; $i < $len; ++$i) {
if (substr($_[0], $i, 1) ne substr($_[1], $i, 1)) {
$n = $i;
last;
}
}
return defined $n ? $n : -1;
}
Are there nice Perl idioms for either of these two tasks?
-bill
P.S. This is not golf, now! I'm *sure* that it is possible to use
some insanely arcane Perl constructs to make the above a *lot* more
succinct, but the results probably would not qualify as "idioms"
in my book. Idioms are pithy, but not terribly obscure. They
don't leave you scratching your head after several minutes of trying
to decrypt them. (I'd say that
select((select(FH), $|=1)[0]);
is the most obscure construct that I'd still be willing to call an
"idiom".)