English 中文(简体)
perl模式匹配数组
原标题:perl pattern match array

我想将我读取的字符串与可能的匹配数组进行匹配。如果它能返回匹配字符串的索引也是很好的。我可以很容易地进行硬编码。。。这一次可能是为了权宜之计,但就一般情况而言,我想看看这是否可能。我浏览了一些书和网上(包括stackoverflow),但找不到我要找的东西,也无法将这些点联系起来,自己也无法弄清楚。

这里有一个我正在寻找的一般事物的例子。。。当然它不起作用,这就是我请求帮助的原因。但我希望这足以推断我的意图。

示例:

my $patterns;
my $line;

my $c = 0 ;
$patterns{$c++} = "$exact" ;  # where the $ in $exact marks the beginning of line.
$patterns{$c++} = "$T?:" ;    # where the ? is the normal wildcard
$patterns{$c++} = "" ;
$patterns{$c++} = "exact" ;

open (FILE, "example.txt") || die "Unable to open file.
";

while (my $line = <IN>) {

  my $idx = -1;
  for ($i=0; $i<$c :$i++) {
    if ($line =~ /$patterns{$i}/ ) { $idx = $i ; }
  }

  $result = $idx;  # of course this will return index of last pattern match, but that s ok
}
close(FILE);
最佳回答

在不知道您正在寻找什么的情况下,这是您的代码转换为实际Perl代码。

use warnings;
use strict;
use autodie; # open and close will now die on failure
use 5.10.1;

my @patterns = (
  qr"^exact",
  qr"^T.?:",
  "",
  "exact",
);

my $result;

open my $fh,  < ,  example.txt ;

while ( my $line = <$fh> ) {
  chomp $line;
  $result = $line ~~ @patterns;
}
close($fh);
问题回答

或者,如果您使用的是perl 5.8而不是5.10,Regexp::Assemble将为您处理此问题:

use strict;
use warnings;
use autodie; # open and close will now die on failure

my @patterns = (
  qr"^exact",
  qr"^T.?:",
  "",
  "exact",
);

my $ra = Regexp::Assemble->new;
$ra->add(@patterns);

my $result;

open my $fh,  < ,  example.txt ;

while ( my $line = <$fh> ) {
  chomp $line;
  $result = $ra->match($line);
}
close($fh);

R: :A也可以设置为告诉您哪些原始模式匹配,我认为5.10智能匹配运算符(~~)不能做到这一点,但这将为您提供实际模式(精确pattern=>;index散列,并使用它来查找匹配模式的索引。





相关问题
Why does my chdir to a filehandle not work in Perl?

When I try a "chdir" with a filehandle as argument, "chdir" returns 0 and a pwd returns still the same directory. Should that be so? I tried this, because in the documentation to chdir I found: "...

How do I use GetOptions to get the default argument?

I ve read the doc for GetOptions but I can t seem to find what I need... (maybe I am blind) What I want to do is to parse command line like this myperlscript.pl -mode [sth] [inputfile] I can use ...

Object-Oriented Perl constructor syntax and named parameters

I m a little confused about what is going on in Perl constructors. I found these two examples perldoc perlbot. package Foo; #In Perl, the constructor is just a subroutine called new. sub new { #I ...

Where can I find object-oriented Perl tutorials? [closed]

A Google search yields a number of results - but which ones are the best? The Perl site appears to contain two - perlboot and perltoot. I m reading these now, but what else is out there? Note: I ve ...

热门标签