Sorry, if this to verbose, but I have a perl script that is partly working. I have a regular expression that extracts either foo|bar
and a prefix on a string given. But the problem is my strings are also FILE NAMES which I also want to open and retrieve its contents like locale_col.dat.2010120813.png
(see Expected Output below).
The output now looks like this:
Content:/home/myhome/col/.my_file_del.mail@locale.foo.org
Key1:foo:Key2:col
Content:/home/myhome/col/.my_file_del.dp1.bar.net
Key1:bar:Key2:col
Content:/home/myhome/jab/.my_file_del.mail@locale.foo.org
Key1:foo:Key2:jab
Content:/home/myhome/jab/.my_file_del.dp1.bar.net
Key1:bar:Key2:jab
I need help tweaking this so that in one pass I can read the list of strings (file names from FileList.txt), extract particular values from the file name path (using regex) and open the file name for its contents. I hope that makes sense or am I looking at breaking this into 2 perl scripts? Thanks for your input.
Code (WIP):
open FILE, "< /home/myname/FileList.txt";
while (<FILE>) {
my $line = $_;
chomp($line);
print "Content:$_"; #This is just printing the filenames.
#I want to get the contents of those file names instead. Stuck here.
if ($line =~ m/home\/myname\/(\w{3}).*[.](\w+)[.].*/){
print "Key1:$2:Key2:$1\n";
}
}
close FILE;
Contents of FileList.txt:
/home/myname/col/.my_file_del.mail@locale.foo.org
/home/myname/col/.my_file_del.dp1.bar.net
/home/myname/jab/.my_file_del.mail@locale.foo.org
/home/myname/jab/.my_file_del.dp1.bar.net
Example content of one of the listed files: (which I need help here with to extract)
$ cat .my_file_del.mail@locale.foo.org
开发者_开发问答locale_col.dat.2010120813.png
Expected Output:
Content:locale_col.dat.2010120813.png
Key1:foo:Key2:col
...
..
Here is a way to do it:
#!/usr/bin/perl
# ALWAYS these 2 lines !!!
use strict;
use warnings;
my $file = '/home/myname/FileList.txt';
# use 3 args open and test openning for failure
open my $FILE, '<', $file or die "unable to open '$file' for reading: $!";
while (my $line = <$FILE>) {
chomp($line);
print "Content:$line\n"; #This is just printing the filenames.
#I want to get the contents of those file names instead. Stuck here.
if ($line =~ m#home/myname/(\w{3}).*[.](\w+)[.].*#) {
open my $file2, '<', $line or die "unable to open '$file' for reading: $!";
while(my line2 = <$file2>) {
print $line2;
}
close $file2;
print "Key1:$2:Key2:$1\n";
}
}
close $FILE;
If you have the filenames, why not open those?
use strict;
use warnings;
use 5.010;
use autodie;
open my $fh, '<', '/home/myname/FileList.txt';
while (my $line = <$fh>) {
chomp $line;
say "Key1:$2:Key2:$1" if m!home/myname/(\w{3})[^.]*[.](\w+)[.].*!;
next unless -e $line; #We skip to the next line unless the file exists
open my $inner_fh, '<', $file;
while (<$inner_fh>) {
say;
}
}
精彩评论