Saturday, October 18, 2008

Learn PPI 2: exchange in condition

as what I posted before, I want to convert
if ( $a eq 'a' ) {
to
if ( 'a' eq $a ) {

PBP encourages it because it's less buggy.

I wrote another script today to fulfill the above request.
http://fayland.googlecode.com/svn/trunk/script/learn_ppi/02ExchangeCondition.pl

things like
my $a = "a";
my $b = "'b'";
my $c = 'c';
my $d = qq~d~;
if ( $a eq "a" ) {
print "1";
} elsif ( $b eq 'b') {
print "2";
} elsif ( $c ne qq~c~) {
print "3";
} elsif ( $c eq q~d~) {
print '4';
} else {
print '5';
}
if ( $a eq $b ) {
print '6';
}
if ( $c eq '$d' ) {
print 7;
}
if ( $a =~ /$b/ ) {
print 8;
}
if ( $a == '$b' or $c == '$d' ) {
print 9;
}
will be converted into
my $a = "a";
my $b = "'b'";
my $c = 'c';
my $d = qq~d~;
if ( "a" eq $a ) {
print "1";
} elsif ( 'b' eq $b ) {
print "2";
} elsif ( $c ne qq~c~) {
print "3";
} elsif ( q~d~ eq $c ) {
print '4';
} else {
print '5';
}
if ( $a eq $b ) {
print '6';
}
if ( '$d' eq $c ) {
print 7;
}
if ( $a =~ /$b/ ) {
print 8;
}
if ( '$b' == $a or '$d' == $c ) {
print 9;
}

I know it's not perfect. it's just a start.

hmm, I'm thinking about packaging the two scripts into modules then uploading to CPAN.
but I can't find a good name(or namespace) for them.

I'll try later.

Thanks and Enjoy!

Labels:

learn PPI 1: double to single

well, I'm very strict on Perl code (more than use strict;).
I want code like my $a = "a"; becomes my $a = 'a'; since it's better.
I'm not considering the speed since it's trivial for " to '. but u'd admit, 'a' is faster than "a".

PPI is really amazing.
it breaks Perl code down into the Perl document/structure we can read and analyze.

To do the task above. I just wrote a script based on PPI.
http://fayland.googlecode.com/svn/trunk/script/learn_ppi/01DoubleToSingle.pl
OK, it's my first time try with PPI, and it's really easy to understand and coding.

Many thanks to Adam Kennedy.

next time, I think I'll deal with
if ( $a eq 'a' ) {
to
if ( 'a' eq $a ) {

I think it's fun. and good to learn a new good thing.

Enjoy and have fun.

Labels: