代码之家  ›  专栏  ›  技术社区  ›  Aakash Goel

如何在Perl中执行常规模式分配?

  •  1
  • Aakash Goel  · 技术社区  · 15 年前
    $ cat names
    projectname_flag_jantemp
    projectname_flag_febtemp
    projectname_flag_marchtemp
    projectname_flag_mondaytemp
    $
    

    my $infile = "names";
    open my $fpi, '<', $infile or die "$!";
    while (<$fpi>) {
        my $temp = # what should come here? #
        func($temp);
    }
    

    我想要临时工

    jan
    feb
    march
    monday
    

    分别。

    模式始终保持不变

    projectname_flag_<>temp
    

    我应该怎么做提取?

    5 回复  |  直到 15 年前
        1
  •  7
  •   FMc TLP    15 年前
    my ($temp) = /^projectname_flag_(.+)temp$/;
    

    请注意,括号 $temp 这样模式匹配就可以在列表上下文中运行。没有他们,

    更一般地,list context中的模式匹配返回捕获的子模式(如果匹配失败,则返回空列表)。例如:

    my $str = 'foo 123   456 bar';
    my ($i, $j) = $str =~ /(\d+) +(\d+)/;  # $i==123  $j==456
    
        2
  •  7
  •   Community Mohan Dere    8 年前

    perl FM's answer (只要通过检查 $month 定义)。

    my $month;
    if ( /^ projectname _flag_ (?<month> [a-z]+ ) temp \z/x ) {
        $month = $+{month};
    }
    
        3
  •  1
  •   codaddict    15 年前
    while (<$fpi>) {
            chomp;
            s{projectname_flag_(.*?)temp}{$1};
            # $_ will now have jan, feb, ...
    }
    
        4
  •  0
  •   SilentGhost    15 年前

    我猜:

    /^projectname_flag_([a-z]+)temp$/
    
        5
  •  0
  •   racke    15 年前
    while (<$fpi>) {
      my ($temp) =($_ =~ m/projectname_flag_(.*?)temp/);
      func($temp);
    }