Search code examples
stringperl

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


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";
@array=<FH>;
foreach $tmp(@array)
{
$b=length($tmp)%3;
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.


Solution

  • 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";
    }
    
    __DATA__
    catbathatxx
    mansunsonx
    0123456789
    012345678