[英]How do I chomp off everything after a character?
I want to create a Perl program to take in a file, and for each line, chomp off everything after a certain character (let's say a /). 我想创建一个Perl程序来接收一个文件,并针对每一行,将某个字符(例如/)后的所有内容都切掉。 For example, consider this example file:
例如,考虑以下示例文件:
foo1/thing 1.1.1 bar
foo2/item 2.3.2 bar
foo3/thing 3.4.5 bar
I want to remove everything after the slash on each line and print it out, so that that file becomes: 我想删除每行斜杠后的所有内容并将其打印出来,以便该文件变为:
foo1
foo2
foo3
I tried to use this program, with readline
in a foreach
loop, but the output was not what I expected: 我尝试使用此程序,并在
foreach
循环中使用readline
,但是输出不是我期望的:
print ( "Enter file name: " ) ;
my $filename = <> ;
$/ = ''
chomp $filename ;
my $file = undef ;
open ( $file, "< :encoding(UTF-8)", $filename
$/ = '/' ;
foreach ( <$file> ) {
chomp ;
print ;
}
But all this does is remove the slashes from each line. 但这只是从每行中删除斜线。
foo1thing 1.1.1 bar
foo2item 2.3.2 bar
foo3thing 3.4.5 bar
How can I alter this to produce the output I need? 如何更改此设置以产生所需的输出?
As far as concerns, the input record separator ( $/
) does not allow regexes. 就问题而言,输入记录分隔符(
$/
)不允许使用正则表达式。
You could proceed as follows: 您可以按以下步骤进行:
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";
}
Regexp s{/.*}{}s
matches on the first slash and everything afterwards, and suppresses it (along with the trailing new line). 正则表达式
s{/.*}{}s
在第一个斜杠和之后的所有斜杠匹配,并抑制它(以及尾随的新行)。
Note: always check for errors when using open()
, as noted in the documentation : 注意:使用
open()
,请务必检查错误,如文档中所述 :
When opening a file, it's seldom a good idea to continue if the request failed, so
open
is frequently used withdie
.打开文件时,如果请求失败,最好不要继续,因此
open
通常与die
。
$line =~ s{/.*}{}s; # In-place (destructive)
要么
my ($extracted) = $line =~ m{([^/]*)}; # Returns (non-destructive)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.