in reply to Matching hyphens in file path to extract zip code

Is the ZIP code always at the beginning of the filename? You can use the core module File::Basename to strip off the path:

use warnings; use strict; use File::Basename qw/fileparse/; my @files = ( '-/yf/-/22211_01_09_2000_XYz.pdf', '_/gt/-/02239_04_04_1989_PkW.pdf', '-/xy/-/02239_04_04_1989_PkW.pdf' ); for my $file (@files) { my $bn = fileparse($file); my ($zip) = $bn =~ /^(\d{5})\D/; print "$file => $zip\n"; }

Replies are listed 'Best First'.
Re^2: Matching hyphens in file path to extract zip code
by Anonymous Monk on Feb 05, 2020 at 15:13 UTC
    I like that option too, just a little more code.
      just a little more code

      Not significantly, I just wrote it more verbosely.

      use File::Basename; my ($zip) = fileparse($file) =~ /^(\d{5})\D/;
        I have to say that is makes the code cleaner and less prone to errors with a long regexp. Thank you!