我有一个类似的帖子(请参阅其他帖子),但从那时起我尝试做的事情略有不同。我正在使用与/79(week\d+[a-z])/i该问题相同的正则表达式匹配。
我有一个包含六行的文件,每行一个不同的路径。例如,包含字符串“cat”的 3 行和包含字符串“dog”的 3 行。
文件.txt
/mypath/sd-urt7-dfc-adfj345h-d0-79week48a-DFC-lk-my_cat.text
/mypath/sd-urt7-afd-parent-79week46d-AFD-lk-my_cat.text
/mypath/sd-urt7-ert-parent-79week50c-ERT-lk-my_cat.text
/mypath/sd-urt7-dfc-adfj345h-d0-79week48a-DFC-lk-my_dog.text
/mypath/sd-urt7-afd-parent-79week46d-AFD-lk-my_dog.text
/mypath/sd-urt7-ert-parent-79week49b-ERT-lk-my_dog.text
Run Code Online (Sandbox Code Playgroud)
我想从每个路径中取出“weekxxX”部分并将其打印到一个文件中。这是我到目前为止所拥有的:
use strict;
use warnings;
use feature qw(say);
use autodie;
open (my $fh, '<', "file.txt") or die "Couldn't open `file.txt`\n";
foreach my $line (<$fh>){ #goes through each line in the file
chomp $line; #chomps new line character from each line
if ($line =~ /cat/) { #if the path includes string "cat"
#use the regex at top of post to get weekxxX of each
#path containing cat and print all 3 weekxxX into
#another file called cat.
open (my $cat, '>', "cat.txt") or die;
print $cat "";
close $cat;
}
elsif ($line =~ /dog/) { #otherwise if the path includes string "dog"3
#use the regex at top of post to get weekxxX of each
#path containing cat and print all 3 weekxxX into
#another file called dog.
open (my $dog, '>', "dog.txt") or die;
print $dog "";
close $dog;
}
}
close $fh;
Run Code Online (Sandbox Code Playgroud)
我认为这可以通过在所有三个路径上使用正则表达式来完成(取决于它是狗还是猫),将所有三周以 weekxxX 格式推送到一个数组中,然后将该数组打印到文件中?我真的不知道如何实现这一点。
use warnings;
use strict;
use feature 'say';
use autodie qw(open);
my $file = shift // die "Usage: $0 filename\n"; #/
# Patterns that determine what file to write to
my ($p1, $p2) = qw(cat dog);
# Open output files, one for each pattern
my %fh_out = map { open my $fh, '>', "$_.txt"; $_ => $fh } ($p1, $p2);
open my $fh, '<', $file;
while (<$fh>) {
if ( my ($week, $type) = /79(week\d+[a-z]).*?($p1|$p2)/i ) {
say {$fh{$type}} $week;
}
}
Run Code Online (Sandbox Code Playgroud)