I’m writing a script that takes a list of files from a directory, opens each one, and then searches for the lines that contain a filename with the .zip extension. Then I want to strip out just the filename from the line. Here is my code:
foreach (@fnames) {
chomp ($_);
open FILE, '<', "$_";
@archives = grep { /.+?\.zip/ } <FILE>;
foreach (@archives) {
if ($_ =~ /("|>)(.+?)("|<)/) { push @files, $2; }
}
}
The files I’m pulling the data from will contain the .zip filenames between either double quotes or angle brackets. This code is returning nothing, but I know the filenames are there. If I do a grep in the terminal I can see all of them, but the grep in Perl isn’t giving me anything. Any ideas?
Possible things wrong:
@fnamesis empty, because of some error in code you are notshowing.
open FILE, ...fails, but since you did not check the return valueof the
open, it fails silently, hence you don’t know about it. Useopen ... or die $!ZIP, and do not usethe
/iignore case option in the grep. Btw,.+?in the beginningis fairly useless, unless you expect unwanted strings that begin with
.zip(i.e. it only checks that there is at least one character before).match.
Also:
open.my @archivesandmy @filesin the proper lexical scope will helpassure you get and keep the data you want.
$_ =~ /.../can simply be written/.../for better readability(IMO).
("|>)is a redundant way of saying[">].grepis redundant processing. You can simply do:In short: