如何更新文件中的每一行

how to update each line in a file

我有一个文件,因为我有一行就像 {<pN_SLOT>,<pN_Port>},用户将给出值 N,例如 N=9 ;然后这些行应该在文件中打印 9 次,并以 N 值递增。 示例:输入文件包含这样的一行 {<pN_SLOT>,<pN_Port>} 然后在输出文件中它应该像这样更新 {<p0_SLOT>,<p0_Port>},{<p1_SLOT>,<p1_Port>},{<p2_SLOT>,<p2_Port>},...upto {<p8_SLOT>,<p8_Port>} . 如果有任何perl模块请建议 任何 help/idea 都将不胜感激 谢谢

这样就可以了:

#!/usr/bin/perl

use strict;
use warnings;

my $count = 9;
for my $num ( 0 .. $count ) {
    print "{<p${num}_SLOT>,<p${num}_Port>},\n";
}

如果您正在获取一个输入文件,并希望将 'N' 替换为 'number',那么您需要的*是一个正则表达式:

#!/usr/bin/perl

use strict;
use warnings;

my $line = '{<pN_SLOT>,<pN_Port>}';
my $count = 9;
for my $num ( 0 .. $count ) {
    my $newline = ( $line =~ s/N/$num/gr ); 
    print "$newline\n";
}

perlre 页面将为您提供更多可用于转换文本的正则表达式。

至于从文件和数字中读入——这实际上是同一个问题。 STDIN 是一个 'standard input' 文件句柄。

您可以使用 <STDIN> 阅读它。

例如

print "Enter Number:\n"; 
my $response = <STDIN>; 
chomp ( $response ); #necessary, because otherwise it includes a linefeed. 

或者从磁盘上的文件读取:

open ( my $input_file, "<", "your_file_name" ) or die $!; 
my $line = <$input_file>;  #note - reads just ONE LINE here. 
chomp ( $line ); 
close ( $input_file ); 

如果您想阅读第二个示例中的多行内容,您可能需要查看 perlvar,尤其是 $/ 运算符。

* 需求很大 - perl 通常有很多方法可以做事。所以在这种情况下 - "need" 表示 "I suggest as a course of action"。