Thanks RE: lexical problems (i think)
Peter Scott
Peter at PSDT.com
Mon Aug 26 17:55:26 CDT 2002
At 03:18 PM 8/26/02 -0700, nkuipers wrote:
>I have one other question, this is related to filehandles.
>
>Take a look at this subroutine. I am warning you right now that it's a
>low-brow way to get the job done, but that's the point.
>
>sub segregate_by_def {
> no strict 'refs'; #ugh
> my $href = shift;
> my @fharray = ('Ava', 'Sma', 'Nhe',
> 'Fok', 'Hpa', 'Tc',
> 'LINE', 'SINE', 'MISC',);
> for my $fh (@fharray) { open $fh, ">>name.${fh}" or die $!; }
> for (keys %$href) {
> if ( / ([SL] (?:ma|INE) |Ava|Nhe|Fok|Hpa|Tc) /x ) {
> my $handle = $1;
> print $handle ">$_\n$href->{$_}\n";
Hmm, you're not testing here that $_ is a key in the hash, I guess you
know your data...
> } else { print MISC ">$_\n$href->{$_}\n"; }
> }
>}
>
>Is this *really* bad?
It could be better... it has me wondering why the filehandle isn't
closed as soon as it's opened since it's a lexical variable... you
don't need to turn off strict refs:
sub segregate_by_def {
my $href = shift;
my %fh;
my @prefs = qw(Ava Sma Nh Fok Hpa Tc LINE SINE);
for (@prefs, 'MISC') {
open my $f, ">>name.$_" or die "open $_: $!\n";
$fh{$_} = $f;
}
my $regex = join '|' => @prefs;
for (keys %$href) {
my $where = /($regex)/o ? $fh{$1} : $fh{MISC};
print $where ">$_\n$href->{$_}\n";
}
}
Not tested... let me know if it doesn't work.
--
Peter Scott
Pacific Systems Design Technologies
http://www.perldebugged.com/
More information about the Victoria-pm
mailing list