-2

Implement a program that processes an input file by changing every occurrence of an old string into a new string. (The usage is: chstr file oldstring newstring, chstr is your program name, file, oldstring and newstring are parameters specified by user.)

if( @ARGV < 2)
{    
print "usage: ReplaceString.pl filename OldString NewString\n";
print "   example: perl ReplaceString.pl intelliquest.txt ";
print "IntelliQuest Kantar > kantar.txt\n";
exit 0;
}
$OldString = $ARGV[1];
$NewString = $ARGV[2];
open(MYFILE,$ARGV[0]) || die "Cannot open file \"$ARGV[0]\"";
while($line = &lt;MYFILE&gt;)
{
$line =~ s/$OldString/$NewString/g;
print STDOUT $line;
}

really not sure what is wrong here, I try and run

jd@jd-laptop:~/Desktop$ perl HW1-2.pl text.txt if the

To replace if with the and i get...

syntax error at HW1-2.pl line 11, near "&lt;"
syntax error at HW1-2.pl line 11, near "&gt"
syntax error at HW1-2.pl line 15, near "}"
Execution of HW1-2.pl aborted due to compilation errors.

Do i need the &lt and &gt? I'm really new to Perl

Thanks in advance

4

2 回答 2

7

无论您基于什么教程,显然都是由一个懒得检查他的工作的人写的。 &lt;&gt;应该分别是<>,但是在某处它被过度的 HTML 编码。

具体来说,线

while($line = &lt;MYFILE&gt;)

应改为:

while($line = <MYFILE>)
于 2013-10-10T19:08:35.257 回答
0

jwodder有答案,但您似乎对此感到困惑:

这适用于我的 Mac。如果你在 Linux、Mac 或 Unix 系统上运行它,你需要我拥有的第一行#! /usr/bin/env perl. 否则,您需要从命令行运行程序perl ReplaceString.pl

在一个 Windows 中,您必须确保.pl后缀映射到您的 Perl 解释器。

#! /usr/bin/env perl

if( @ARGV < 2) {    
    print "usage: ReplaceString.pl filename OldString NewString\n";
    print "   example: perl ReplaceString.pl intelliquest.txt ";
    print "IntelliQuest Kantar > kantar.txt\n";
    exit 0;
}
$OldString = $ARGV[1];
$NewString = $ARGV[2];

open(MYFILE,$ARGV[0]) || die "Cannot open file \"$ARGV[0]\"";

while( $line = <MYFILE> ) {
    chomp $line;
    $line =~ s/$OldString/$NewString/g;
    print "$line\n";
}

我认为你在上课和学习 Perl。

我只是好奇你在哪里学习 Perl。这是我希望在旧的 Perl 3.x 时代看到的语法。从那时起,Perl 有了很大的进步,我认为你的老师会帮助你学习新的语法风格。

于 2013-10-10T19:49:50.840 回答