Perl语法错误:用于读取文件的示例程序

时间:2011-11-07 13:39:06

标签: perl syntax-error

我在阅读文件时遇到错误,下面是脚本。

#!/bin/bash
$file = "SampleLogFile.txt";    #--- line 2 
open(MYINPUTFILE,$file);        #--- line 3  
while(<**MYINPUTFILE**>) { 

# Good practice to store $_ value because
# subsequent operations may change it.
my($line) = $_;

# Good practice to always strip the trailing
# newline from the line.
chomp($line);

# Convert the line to upper case.
print "$line" if $line = ~ /sent/;

}
close (MYINPUTFILE);

输出

PerlTesting_New.ksh [2]:=:未找到
PerlTesting_New.ksh [3]:第3行的语法错误:`('意外

知道问题是什么吗?

3 个答案:

答案 0 :(得分:5)

更改

#!/bin/bash

#!/usr/bin/perl

否则Perl将不会解释您的脚本。根据您的系统相应地更改路径

答案 1 :(得分:1)

好的,无论是谁教你写这样的Perl,都需要走出九十年代。

#!/usr/bin/perl

use strict;   # ALWAYS
use warnings; # Also always.  

# When you learn more you can selectively turn off bits of strict and warnings
# functionality  on an as needed basis.


use IO::File; # A nice OO module for working with files.

my $file_name = "SampleLogFile.txt"; # note that we have to declare $file now.

my $input_fh = IO::File->new( $file_name, '<' );  # Open the file read-only using IO::File.

# You can avoid assignment through $_ by assigning to a variable, even when you use <$fh>   

while( my $line = $input_fh->getline() ) { 

    # chomp($line); # Chomping is usually a good idea.  
                    # In this case it does nothing but screw up 
                    # your output, so I commented it out.

    # This does nothing of the sort:
    # Convert the line to upper case.
    print "$line" if $line = ~ /sent/;

}

你也可以用一个班轮来完成这个:

perl -pe '$_ = "" unless /sent/;'  SampleLogFile.txt

有关单行的更多信息,请参阅perlrun

答案 2 :(得分:0)

嗯,你的第一行:#!/ bin / bash

/ bin / bash:这是Bash shell。

您可能需要更改为

!在/ usr / bin中/ perl的