Saturday, March 16, 2013

Chomp vs Chop in Perl

use strict;
use warnings;

#The difference between chomp and chop is that chomp only removes newlines

my $test = "123\n";
print "Original: " . $test . " Chomped: " . chomp($test);

#chop doesn't care what it removes
do {
    print "Iterating: $test\n";
} while (chop($test) ne "");

#outputs:
#Original: 123
# Chomped: 1Iterating: 123
#Iterating: 12
#Iterating: 1
#Iterating:
Next is a slightly more elegant way to take user input and chop the last part of it. End the loop with ^D or ^C (EOF will give you a undefined error that we fix in the next bit of code).
use strict;
use warnings;

while (chomp(my $test = <STDIN>)) {
    last if $test eq "";
    do {
        print "$test\n";
    } while (chop($test) ne "");
}
#outputs:
#antidisestablishmentarianism
#antidisestablishmentarianism
#antidisestablishmentarianis
#antidisestablishmentariani
#antidisestablishmentarian
#antidisestablishmentaria
#antidisestablishmentari
#antidisestablishmentar
#antidisestablishmenta
#antidisestablishment
#antidisestablishmen
#antidisestablishme
#antidisestablishm
#antidisestablish
#antidisestablis
#antidisestabli
#antidisestabl
#antidisestab
#antidisesta
#antidisest
#antidises
#antidise
#antidis
#antidi
#antid
#anti
#ant
#an
#a
#
The following will make a very inefficient reverse function, but as you can see chop's return value is the tail of the string.
use strict;
use warnings;

my @reverso = ();
while (defined (my $test = <STDIN>)) {
    chomp($test);
    last if $test eq "";
    my $tail;
    do {
        print "$test\n";
        $tail = chop($test);
        push @reverso, $tail;
    } while ($tail ne "");
}

print @reverso;
#end the loop with EOF!
#msinairatnemhsilbatsesiditna

No comments:

Post a Comment