![](/img/trans.png)
[英]How do I use correctly chomp command to get rid of \n character in perl?
[英]How do I chomp off everything after a character?
我想创建一个Perl程序来接收一个文件,并针对每一行,将某个字符(例如/)后的所有内容都切掉。 例如,考虑以下示例文件:
foo1/thing 1.1.1 bar
foo2/item 2.3.2 bar
foo3/thing 3.4.5 bar
我想删除每行斜杠后的所有内容并将其打印出来,以便该文件变为:
foo1
foo2
foo3
我尝试使用此程序,并在foreach
循环中使用readline
,但是输出不是我期望的:
print ( "Enter file name: " ) ;
my $filename = <> ;
$/ = ''
chomp $filename ;
my $file = undef ;
open ( $file, "< :encoding(UTF-8)", $filename
$/ = '/' ;
foreach ( <$file> ) {
chomp ;
print ;
}
但这只是从每行中删除斜线。
foo1thing 1.1.1 bar
foo2item 2.3.2 bar
foo3thing 3.4.5 bar
如何更改此设置以产生所需的输出?
就问题而言,输入记录分隔符( $/
)不允许使用正则表达式。
您可以按以下步骤进行:
print ( "Enter file name: " ) ;
my $filename = <> ;
chomp $filename ;
open ( my $file, "< :encoding(UTF-8)", $filename )
or die "could not open file $filename: $!";
while ( my $line = <$file> ) {
$line =~ s{/.*}{}s;
print "$line\n";
}
正则表达式s{/.*}{}s
在第一个斜杠和之后的所有斜杠匹配,并抑制它(以及尾随的新行)。
打开文件时,如果请求失败,最好不要继续,因此
open
通常与die
。
$line =~ s{/.*}{}s; # In-place (destructive)
要么
my ($extracted) = $line =~ m{([^/]*)}; # Returns (non-destructive)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.