I had a similar post on this (see other post), but what I am trying to do has slightly varied since then. I am using the same regex matching /79(week\d+[a-z])/i from that question.
I have a file that contains six lines, each line a different path. As an example, there are 3 lines including the string "cat" and 3 lines including the string "dog".
file.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
I want to take the "weekxxX" portion out of each path and print it out into a file. Here is what I have so far:
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;
I am thinking this can be done by using regex on all three paths (depending on whether it is dog or cat), push all three weeks in format weekxxX into an array and then print that array into the file? I'm really not sure how to implement this.
cat.txtanddog.txtneed to be in quotes.$lineinto the files. You also need to open the files in append mode, so you don't overwrite the previous lines.autodiedoes that (what I incidentally used in my answer here while I normally don't). But then you don't needor dieat all -- which is why I commented, seeingdiewithout$!. I'd suggest to include thatuse autodie;in your code here (I'd comment if there weren'tdieat all, too :), along withwarningsandstrict-- you'll invariably get comments when they're missing.