我自己学习Perl,我想从文本文件中读取并更改其中的一部分。假设我的文本文件看起来像这样,我想将价格提高10%:
Item Price
Jeans 50
Blazer 100
Suit 140
这是我到目前为止编写的代码 - 我是初学者,所以请保持温柔:
#!/usr/bin/perl
use warnings;
use strict;
use diagnostics;
open (IN,'Resources\shop.txt') or die "Can't open input file: $!";
open (OUT,">",'Resources\discount.txt') or die "Can't open output file: $!";
while (<IN>) {
chomp;
my @sections = split(/\t/);
my $prices = ($sections[1]);
$prices = (($prices)*1.1);
print OUT "$_\n";
}
答案 0 :(得分:5)
您实际上无法随时更改$_
,因此您可以打印任何内容。
该print
行应该是:
print OUT join ("\t", $sections[0], $prices ),"\n";
虽然实际上,你应该:
open ( my $in, '<', 'Resources\shop.txt' );
split
进入数组,然后分配该值,然后更改它 - 尝试my @fields = split ( /\t/ ); $fields[1] *= 1.1; print OUT join "\t", @fields;
所以:
#!/usr/bin/perl
use warnings;
use strict;
use diagnostics;
open( my $input, '<', 'Resources\shop.txt' )
or die "Can't open input file: $!";
open( my $output, '>', 'Resources\discount.txt' )
or die "Can't open output file: $!";
while (<$input>) {
chomp;
my @sections = split(/\t/);
$sections[1] *= 1.1 if $sections[1] =~ m/\d/;
print {$output} join "\t", @sections, "\n";
}
close ( $input ) or warn $!;
close ( $output ) or warn $!;
答案 1 :(得分:1)
对于读取文本文件和更改其中一部分这样的简单任务,通常最好使用单行进行就地编辑:
perl -ne '@s=split /\t/;if ($s[1]=~/^[\d.]+$/) {printf "$s[0]\t%f\n",$s[1]*1.1} else {print}' input_file.txt >output_file.txt
请参阅perl --help
和perldoc perlrun
了解-n,-i和-p开关