PerlMusings

Note: You are viewing an old revision of this page. View the current version.

Perl Musings

A couple of small items got me thinking enough this week that I decided they would make a good blog post. Disclaimer: I am a terrible hack of a perl programmer. I write horrible sysadmin scripts in perl. At the same time I love the language and am always striving to learn more. One thing I love about my code review fetish is it gives me a lot of opportunities to learn from others.

First up: what's the best way to write a loop that could execute an unknown number of times? I think that if you know a loop will execute 5 times, you should do this:

for ($i=1; $i<6; $i++)
{
  # stuff gets REAL
}

Pretty simple, right? $i starts at 1, gets incremented each time, and the loop exits after the fifth iteration.

But what if you want to increment $i on each iteration, but not use it as the exit condition? Say for example you are going to do something in a loop forever, until some external event kicks you out? I was codereviewing a coworker's code the other day, and he used this:

for ($i=0; 1; $i++)

That ust looks weird as hell to me. To be fair, that might must be because I first learned about for loops in C. I actually had to scratch my head a moment on that one.

Of course, what he's really doing is using a for loop to increment $i forever. The test condition (1) will always be true, so the loop will just continue on ad infinitum. This works fine because this look actually gets called inside an alarm timer, so after 30 seconds it stops no matter what.

A couple things I want to ponder for a blog post vs

while($i++)

which is better?

and talk about using the (? non-capture modifier in regexp matches

($package) = (/add yinst (?:pkg|package) (\S+)/);


Our Founder
ToolboxClick to hide/show
RecentChanges Click to hide/show