The documentation for Perl's split()
function says this:
If LIMIT is omitted (or, equivalently, zero), then it is usually treated as if it were instead negative but with the exception that trailing empty fields are stripped (empty leading fields are always preserved)
So, the default behaviour of split()
is to remove trailing empty fields. We can then use join()
to regenerate the original record minus any trailing delimiters.
So it can be as simple as:
# Note that '|' has a special meaning in regexes, so we
# need to escape it, using '\'.
my $output_line = join '|', split /\|/, $input_line;
Or, putting it in a complete program that reads from STDIN
and writes to STDOUT
:
#!/usr/bin/perl
use strict;
use warnings;
use feature 'say';
while (<>) {
chomp;
say join '|', split /\|/;
}
If you put that in a file called rmtrailing
, then it can be run from a command line like this:
$ perl rmtrailing < your_input_file.txt > your_output_file.txt