【问题标题】:How to Pass more than one file in perl MY function [Perl]如何在 perl MY 函数中传递多个文件 [Perl]
【发布时间】:2022-10-14 06:38:16
【问题描述】:

我是 Perl 的新手,想知道你们是否可以帮助我在下面的代码中传递多个文件;

my @files=<data/j*.*.txt>;
if (@ARGV) {
  my $test=$ARGV[0];
  $test=lc($test);
  print "Using $test instead\n";
  @files=</data/$test*.*.txt>;
  print "Found @files instead\n";
}
my $outfile='/data/w_c.txt';
my $lotfile='/data/completed.txt';
if (-e $outfile) {
  unlink $outfile;
}

在上面的代码(my @files=&lt;data/j*.*.txt&gt;;)中,当前所有文件都以j*.* 开头,但我只想传递以下所有文件;

  • j*.1.txt
  • c*.3.1.txt
  • a*.a.b.txt
  • 等..

我如何在程序本身中传递文件列表?我正在尝试读取所有这些文件并从中提取信息..!

先感谢您..

【问题讨论】:

  • 交叉发布到PerlMonks
  • 您将文件名传递到的这个函数在哪里?

标签: bash perl


【解决方案1】:

你可以使用这样的东西:

<data/j*.*.txt data/j*.1.txt data/a*.a.b.txt>

有一点可能最好使用&lt;data/*.txt&gt; 并使用正则表达式来过滤除您想要的之外的所有内容。

【讨论】:

  • 如果我像您提到的“过长 <> 运算符”那样使用它,我会收到此错误
  • @prad001,阅读其余答案。
  • 我怎样才能只过滤以下值? /data/j*.gox.txt /data/j*.gox1.txt /data/j*.vtf.txt /data/j*.vtf1.txt /data/j*.vtf2.txt /data/j* .vtff.txt /data/j*.vtfl.txt /data/j*.hci.txt /data/j*.hci1.txt /data/j*.hci2.txt /data/j*.hcif.txt /数据/j*.hcil.txt /data/j*.iso.txt /data/j*.iso1.txt /data/j*.iso2.txt /data/j*.tox.txt /data/j*. ono.txt /data/j*.ild1.txt /data/j*.ild2.txt
  • 使用&lt;data/*.txt&gt; 并使用正则表达式过滤掉除您想要的之外的所有内容。
  • 你是什​​么意思正则表达式过滤掉..?你能给我一些例子吗?我是新手。。
【解决方案2】:

而不是以这种方式使用 glob,我很想切换到 opendirreaddir 并在正则表达式中使用模式数组交替选择我的文件。这样一来,您就不会在相同的短 sn-p 代码中使用两种不同的文本通配符语法(用于 glob 和用于 regex),我以前曾见过这让刚接触 Perl 的程序员感到困惑。

# Set your data directory.
my $dir = '/data';

# Take the whole array of arguments on the command line as patterns to
# match in the regex, or default to a short list of patterns if there
# are none.
# (Consider using an options library later rather than messing
# with @ARGV directly if the program becomes more complex.)
my @filespecs = ( scalar @ARGV ? @ARGV : qw( j.*?.1.txt c.*?.3.1.txt ) );

# Join the multiple patterns with the regex alternation character.
# This makes them multiple matching options in a single regex.
my $re = join '|', @filespecs;

# Open the directory for reading, or terminate with an error.
opendir my $d, $dir or die "Cannot open directory $dir : $!
";

# Select into the @files array things read from the directory
# entry that are regular files (-f), do not start with '.',
# and which match the regex.
my @files = grep { (-f) && (!/^./) && (/$re/) } readdir $d;

# Close the directory handle now that we're done using it.
closedir $d;

如果没有过于冗长的 cmets,就可以归结为这一点。

my $dir = '/data';
my @filespecs = ( scalar @ARGV ? @ARGV : qw( j.*?.1.txt c.*?.3.1.txt ) );
my $re = join '|', @filespecs;

opendir my $d, $dir or die "Cannot open directory $dir : $!
";
my @files = grep { (-f) && (!/^./) && (/$re/) } readdir $d;
closedir $d;

我省略了原始代码的最后几行,因为它似乎与您的问题没有直接关系。

您阅读的一些资料可能有助于理解此解决方案。:

【讨论】:

    猜你喜欢
    • 2014-04-09
    • 1970-01-01
    • 2013-11-15
    • 1970-01-01
    • 1970-01-01
    • 2011-09-06
    • 1970-01-01
    • 2022-01-11
    • 2012-05-18
    相关资源
    最近更新 更多