0

对不起,如果这很冗长,但我有一个部分工作的 perl 脚本。我有一个正则表达式,可以提取其中一个foo|bar和给定字符串的前缀。但问题是我的字符串也是文件名,我也想打开并检索它的内容locale_col.dat.2010120813.png(见下面的预期输出)。

输出现在如下所示:

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

我需要帮助来调整它,以便一次性读取字符串列表(来自 FileList.txt 的文件名),从文件名路径中提取特定值(使用正则表达式)并打开文件名以获取其内容。我希望这是有道理的,还是我正在考虑将其分解为 2 个 perl 脚本?感谢您的输入。

代码(在制品):

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;

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

列出的文件之一的示例内容:(我需要帮助来提取)

$ cat .my_file_del.mail@locale.foo.org 
locale_col.dat.2010120813.png

预期输出:

Content:locale_col.dat.2010120813.png
Key1:foo:Key2:col
...
..
4

2 回答 2

3

如果你有文件名,为什么不打开那些?

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;
    }
}
于 2010-12-10T18:18:34.910 回答
3

这是一种方法:

#!/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;
于 2010-12-10T18:20:21.517 回答