如何在perl中读取行

如何在perl中读取行

本文介绍了如何在perl中读取行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我对Perl脚本非常陌生,并且陷入了困境.

我的要求是我有一个文本文件,应将其作为输入作为perl脚本的输入.我想逐行阅读文本文件并找到一种模式.一旦找到模式,就应该用另一个字符串替换.

我想要三件事:-

1)输出应覆盖到同一文件.

2)输出应定向到单独的文件.

3)如何使用参数运行Perl脚本.

我的代码如下所示,它不起作用:

Hi,

I am very new to perl scripting and am stuck in something.

My requirement is that i have a text file which should be given as input to the perl script as an argument. I want to read the text file line by line and find a pattern. Once i find a pattern i should replace it by another string.

I want 3 things:-

1) output should overwritten onto the same file.

2) output should be directed to a seperate file.

3) how to run a perl script taking arguments.

My code is as below which doesn''t work :

#!/usr/bin/perl

chomp($arg1=@ARGV[0]);

print "Enter the name of the tag to be replaced\n";
$inp1=<STDIN>;
print "Enter the new tag name \n";
$out=<STDIN>;

open(INPUTFILE,$arg1);

while(<INPUTFILE>)
{
        my($line) = $_;
        $line= ~ s/$inp1/$out/g;
}




我将其运行为:

/.replace.pl test.txt

其中replace.pl是perl脚本,而test.txt是作为参数给出的文件.

如果上述代码有误,可以有人为我编写一个新代码(必须由像我这样的初学者理解).

请尽快回复,因为我被卡住了.任何帮助将不胜感激.

在此先感谢





甚至我现在都尝试了一些新的东西.代码如下:




and i am running it as:

/.replace.pl test.txt

where replace.pl is the perl script and test.txt is the file given as argument.

In case the above code is wrong , can someone write a new code for me(must be understood by a begginer like me).

Please reply ASAP coz i am stuck uo badly.Any help would be appreciated.

Thanks in advance





Even i tried something new now. The code is as below:

#!/usr/bin/perl -w
use strict;
use FileHandle;
print "Enter the name of the tag to be replaced \n";
$inp=<STDIN>;
print "Enter the new tag name \n";
$out=<STDIN>;
$arg1=chomp(@ARGV[0]);
sub printFile($)
{
        my $fileHandle = $_[0];
        while(<fileHandle>)
        {
                my $line=$_;
                $line =~ s/$inp/$out/;
        }
}

my $fh = new FileHandle;
$fh->open($arg1) or die "Could Not Open the File\n";
printFile($fh);
$fh->close();





但是它显示出很多错误.错误如下:





But its showing a lot of errors. The errors are as below :

Global symbol "$inp" requires explicit package name at ./replace2.pl line 5.
Global symbol "$out" requires explicit package name at ./replace2.pl line 7.
Global symbol "$arg1" requires explicit package name at ./replace2.pl line 8.
Global symbol "$inp" requires explicit package name at ./replace2.pl line 15.
Global symbol "$out" requires explicit package name at ./replace2.pl line 15.
Global symbol "$arg1" requires explicit package name at ./replace2.pl line 20.
Execution of ./replace2.pl aborted due to compilation errors.




我正在尝试将其作为./replace2.pl test.txt
运行

请帮忙.

也不要忘记第一个代码.

谢谢




I am trying to run it as ./replace2.pl test.txt


Please help.

Also dont forget the 1st code.

Thanks

推荐答案




这篇关于如何在perl中读取行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 17:55