Perl:如何指定以" /"开头的行;

时间:2017-09-26 20:34:59

标签: perl

我有一个名为list.txt的文件,看起来像这样:(它有超过500行)

/apps/gtool/0.7.5/gtool -M --g gen1.txt etc
/apps/gtool/0.7.5/gtool -M --g gen2.txt etc
/apps/gtool/0.7.5/gtool -M --g gen3.txt etc

我想用list.txt的每一行制作.sh脚本。我可以在Perl中执行此操作,但我有一个问题,因为我不知道如何指定/开头的行

我的脚本如下:

use strict;
use warnings;

open (IN, "<list_for_merging_chunks.sh");
while (<IN>)
{
    if ($_=~ m/^/apps.*\n/)
    {
    my $file = $_;
    $file =~ s/.*\> //;
    $file =~ s/\.txt/.sh/;
    $file =~ s/\n//;
    open (OUT, ">$file");
    print OUT "\#!/bin/bash\n\#BSUB -J \"$file\"\n\#BSUB -o 
/scratch/home/\n\#BSUB -e /scratch/home/$file\.out\n#BSUB -n 1\n\#BSUB -q 
normal\n\#BSUB -P DBCDOBZAK\n\#BSUB -W 168:00\n";
    print OUT $_;
    close OUT;
    }

}

exit;

我收到错误:

Bareword found where operator expected at merging_chunks.pl line 7, near "*\n"
    (Missing operator before n?)
"my" variable $file masks earlier declaration in same statement at 
merging_chunks.pl line 10.
"my" variable $file masks earlier declaration in same scope at 
merging_chunks.pl line 11.
"my" variable $file masks earlier declaration in same scope at 
merging_chunks.pl line 12.
"my" variable $file masks earlier declaration in same scope at 
merging_chunks.pl line 14.
"my" variable $file masks earlier declaration in same scope at 
merging_chunks.pl line 15.
"my" variable $file masks earlier declaration in same statement at 
merging_chunks.pl line 15.
"my" variable $file masks earlier declaration in same statement at 
merging_chunks.pl line 15.
"my" variable $_ masks earlier declaration in same scope at merging_chunks.pl 
line 16.
syntax error at merging_chunks.pl line 7, near "*\n"
syntax error at merging_chunks.pl line 20, near "}"
Execution of merging_chunks.pl aborted due to compilation errors.

我认为这与此文件有关:if ($_=~ m/^/apps.*\n/) 它似乎不喜欢它以/开头的事实。无论如何我可以解决这个问题吗?我假设有一个特殊的角色我可以用来以某种方式告诉Perl?非常感谢。

2 个答案:

答案 0 :(得分:2)

您可以使用黑色斜线转义正则表达式中的元字符。

m/^\/apps.*\n/

您也可以像这样更改模式匹配的分隔符。

m{^/apps.*\n}

您似乎知道这一点,因为您已经在代码中的下面的双引号字符串中完成了它。

请注意,如果您使用$_ =~,则不需要$_部分。如果您使用m//,则隐含在$_

答案 1 :(得分:1)

使用regexpr中未使用的字符更改regexpr分隔符。在此示例中,我使用!代替/

$_=~ m!^/apps.*\n!

或scape / character:

$_ =~ m/^\/apps.*\n/