Reputation: 2064
I'm reading from a directory and I'm searching for file names and extensions. The only extension accepted are in
and out
. If I get a positive match I add the gathered information into an hash.
Let's say that this hash can be something like this:
#{
# filename1 => {
# in => 1|0
# out => 1|0
# },
# ...,
# filenameN => {
# in => 1|0,
# out => 1|0
# }
#}
I'm doing all of the above using this snippet:
...
while ( my $file = readdir INDIR ) {
my ( $file_name, $file_ext ) = $file =~ /^(\w+)\.([^.]+)$/;
next if not( $file_name and $file_ext );
next if not( $file_ext =~ /in|out/ );
$hash{$file_name}->{$file_ext} = 1;
}
...
I was wondering if there is a better way to achieve the same desired result, maybe i.e. cascading not two next if
statements.
Have you some suggestion to simplify that snippet?
Upvotes: 0
Views: 68
Reputation: 35198
Building on mpapec's solution, I prefer the control flow functions at the start of the line.
while ( my $file = readdir INDIR ) {
next if $file !~ /^(\w+)\.(in|out)$/;
$hash{$1}{$2} = 1;
}
Or perhaps more clear as:
while ( my $file = readdir INDIR ) {
if ($file =~ /^(\w+)\.(in|out)$/) {
$hash{$1}{$2} = 1;
}
}
Upvotes: 2
Reputation: 50637
You can wipe out both if
conditions with,
my ($file_name, $file_ext) = $file =~ /^(\w+)\.(in|out)$/ or next;
or letting module do the file parsing,
use File::Basename;
# ..
my ($file_name,undef,$file_ext) = fileparse($file, "in", "out");
next if !$file_ext;
Upvotes: 3