Using Perl to remove n characters from the end of multiple lines

Go To


I want to remove n characters from each line using PERL.

For example, I have the following input:

catbathatxx (length 11; 11%3=2 characters) (Remove 2 characters from this line)

mansunsonx (length 10; 10%3=1 character) (Remove 1 character from this line)

#!/usr/bin/perl -w
open FH, "input.txt";
foreach $tmp(@array)
my $c=substr($tmp, 0, length($tmp)-$b);
print "$c\n";

I want to output the final string (after the characters have been removed).

However, this program is not giving the correct result. Can you please guide me on what the mistake is?

Thanks a lot. Please let me know if there are any doubts/clarifications.

2012-04-04 17:31
by zock


I am assuming trailing whitespace is not significant.

#!/usr/bin/env perl

use strict; use warnings;

use constant MULTIPLE_OF => 3;

while (my $line = <DATA>) {
    $line =~ s/\s+\z//;
    next unless my $length = length $line;
    my $chars_to_remove = $length % MULTIPLE_OF;
    $line =~ s/.{$chars_to_remove}\z//;
    print $line, "\n";

2012-04-04 19:52
by Sinan Ünür
Thanks. The code is giving the correct output - zock 2012-04-05 04:39


The \K regex sequence makes this a lot clearer; it was introduced in Perl v5.10.0.

The code looks like this

use 5.10.0;
use warnings;

for (qw/ catbathatxx mansunsonx /) {
  (my $s = $_) =~ s/^ (?:...)* \K .* //x;
  say $s;


2012-04-05 17:46
by Borodin


In general you would want to post the result you are getting. That being said...

Each line in the file has a \n (or \r\n on windows) on the end of it that you're not accounting for. You need to chomp() the line.

Edit to add: My perl is getting rusty from non-use but if memory serves me correct you can actually chomp() the entire array after reading the file: chomp(@array)

2012-04-04 17:35
by Brian Roach
That is correct Bria - Borodin 2012-04-04 20:11


You should use chomp() on your array, like this:

2012-04-04 17:37
by levif


perl -plwe 'chomp; $c = length($_) % 3; chop while $c--' < /tmp/zock.txt

Look up the options in perlrun. Note that line endings are characters, too. Get them out of the way using chomp; re-add them on output using the -l option. Use chop to efficiently remove characters from the end of a string.

2012-04-04 18:01
by Lumi