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

Friday, March 15, 2013

What I Learned about Perl Today

Today I ran into an issue where I needed to redirect STDERR to STDOUT in a Perl script. So, I figured the easiest way would be to redirect those two files somehow. Perl provides a relatively elegant way to do so. Running open(STDERR, '>&STDOUT') will do the trick by overwriting the STDERR filehandle with a duplicate of the STDOUT filehandle in writing mode. In the Perl open documentation, the examples show the programmer saving the previous STDERR filehandle and restoring it at the end of the interactions, but I didn't require any such thing because the script ends after execution.