Reputation: 175
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?
Upvotes: 1
Views: 242
Reputation: 222592
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 withdie
.
Upvotes: 3
Reputation: 386406
$line =~ s{/.*}{}s; # In-place (destructive)
or
my ($extracted) = $line =~ m{([^/]*)}; # Returns (non-destructive)
Upvotes: 3