[Tutor] Are you allowed to shoot camels? [kinda OT]

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Thu Feb 3 03:19:26 CET 2005



On Thu, 3 Feb 2005, Liam Clarke wrote:


> Had the *ahem* joy of learning Perl last night. Egad. Wrote the script
> in Python to get it right, and then 'translated' it to Perl.


Hi Liam,


I strongly recommend sending the Perl code to that Perl-beginners mailing
list referenced earlier.  I'm sure that there are some Perl idioms that
can simplify the code there.


For example:

### Perl ###
$wrkDir = "c:/python23/j/j2";
opendir( TGTDIR, $wrkDir);
@dirList = readdir(TGTDIR);
@moddirList=();
foreach $fileName (@dirList) {
    if ($fileName ne ".." && $fileName ne ".") {
        @moddirList = (@moddirList, $fileName);
    }
}
######


can be greatly improved by Perl's globbing operator instead of readdir():

######
$wrkDir = "c:/python23/j/j2";
@dirList = <$wrkDir/*>;
######


This has a fairly close Python equivalent in the glob.glob() function:

###
wrkDir = "s:/toolkit/retain/sustainableEmployment"
dirList = glob.glob(wrkDir + "/*")
###



> @someArray = (@someArray, $newValue) is the same as someArray.append(newValue)

This is actually doing much more work than a list append.  The list-adding
code that you had earlier is equivalent to:

### Python ###
someList = someList + [newValue]
######

which is just bad.  *grin*


More idiomatic Perl is:

### Perl ###
push @someArray, $newValue;
######

which should have the same performance as a list append().



> Of course, the documentation I had didn't mention that. It just said to
> open it and use print FILEHANDLE $value; to write.

Perl's documentation system 'perldoc' command is one of the really nice
things about Perl.  In some cases, I think it might be even more
comprehensive than 'pydoc', since perldoc also directly links to tutorial
material.

Try:

###
$ perldoc perl
###



I guess I'm trying to say: language idioms take time to learn, and unlike
syntax errors, weird idioms aren't really detectable by the runtime
system.  *grin*

If you continue to learn Perl, talk with the beginners's group there, so
that the community there can help.  And if the Perl programs that you're
writing seem suboptimal, get it vetted by someone who knows Perl well; you
may be pleasantly surprised.


Best of wishes to you!



More information about the Tutor mailing list