LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   [Perl] chop last char from line (https://www.linuxquestions.org/questions/programming-9/%5Bperl%5D-chop-last-char-from-line-530112/)

noir911 02-18-2007 06:49 AM

[Perl] chop last char from line
 
My code is to delete last character (if last char is M or K) from a file. But it's printing out both the chop and un-chop result

Here's the output

Quote:


new file: 10M
new file: 10
new file: 100M
new file: 100
new file: 100K
new file: 100
new file: 200K
new file: 200

Here's the code

Code:

#!/usr/local/bin/perl

my $file = "weekly.log";

# string to chop from log
my @strip = qw(M K);

open (FILE, "$file") or die "can't open $file: $!";

while (<FILE>)
{
    foreach $strip(@strip)
    {
        chop;
        print "new file: $_\n";
    }
}


matthewg42 02-18-2007 10:00 AM

You have two elements in the array @strip, and you iterate over then and on each iteration print the line... Move the print to outside of the foreach block. Also consider using a regular expression substitution:
Code:

while(<FILE>)
{
    s/[MK]$//;
    print;
}


cfaj 02-18-2007 10:11 PM

Quote:

Originally Posted by noir911
My code is to delete last character (if last char is M or K) from a file. But it's printing out both the chop and un-chop result

Here's the output

Here's the code

Code:

#!/usr/local/bin/perl

I would use awk rather than perl:

awk '{ sub(/[MK]$/,""); print }' "$FILENAME"

matthewg42 02-19-2007 02:38 AM

Quote:

Originally Posted by cfaj
I would use awk rather than perl:

awk '{ sub(/[MK]$/,""); print }' "$FILENAME"

awk is nice too, but I find it is slower for some operations. I once wrote some nice pretty reports using awk, which summarized many gigabytes of data. They were very nice - awk made implementing them a pleasure. Out of curiosity, one day, I fed my awk script through a2p - the automatic code converter from awk to perl. I ran the new perl script on the same input data, and it ran in less than half the time. Since then I haven't really used awk, apart from command-line one-liners.

Apart from my (very non-scientific) assessment of perl's superior performance, my biggest gripe with awk is this business of having whitespace as an operator in the language (string concatenation). I don't like this, although it is just a matter of personal taste.

bigearsbilly 02-19-2007 05:47 AM

true lazy perl... :)
Code:

#!/usr/local/bin/perl -p

BEGIN {@ARGV = "weekly.log"}
s/[MK]$//;


matthewg42 02-19-2007 06:10 AM

even lazier perl:
Code:

$ perl -npe 's/[MN]$//;' input_file > output_file

bigearsbilly 02-19-2007 07:47 AM

even lazier perl
Code:

$ perl -pe 's/[MN]$//;' input_file > output_file

superfluous -n switch ;)

matthewg42 02-19-2007 08:29 AM

I bow to your expert laziness!

kshkid 02-20-2007 11:16 PM

Code:

sed 's/[MK]//g' b


All times are GMT -5. The time now is 05:29 PM.