Question

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?

Était-ce utile?

La solution

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;

Autres conseils

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;
    }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top