简体   繁体   中英

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 /). 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:

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).

Note: always check for errors when using open() , as noted in the documentation :

When opening a file, it's seldom a good idea to continue if the request failed, so open is frequently used with die .

$line =~ s{/.*}{}s;                       # In-place (destructive)

要么

my ($extracted) = $line =~ m{([^/]*)};    # Returns (non-destructive)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM