Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: Looping made easy...

by thelenm (Vicar)
on Jul 22, 2003 at 17:06 UTC ( [id://276821]=note: print w/replies, xml ) Need Help??


in reply to Looping made easy...

A couple of comments on the specific code example you posted, hopefully they will be helpful to you...

If I'm going to be doing something a specific number of times, or if I need a loop counter, I often write a for loop over a range, rather than a while loop. For example, for my $i (0..89) instead of my $i=0; while ($i <= 89) { ... ++$i }. I find that this greatly simplifies things and makes the code's purpose readable and clear (except that 89 is still a magic number - why 89?).

Variables should have the smallest scope possible. So instead of using $a, etc. as globals and then resetting their values at the top of the loop, just declare them as lexical variables. For example, my ($a, $b, $c, $d); instead of $a=''; $b=''; etc. Of course, it goes without saying that you should probably have better variable names that indicate what they are actually used for. And $a and $b are special variables used by Perl's sort routine, so you should avoid those specific variable names unless you know exactly why you are using them.

You can avoid having named variables if you are just going to throw away what gets assigned to them. You don't seem to be using $a, $c, $d, or $i, so you can get away without declaring them at all.

$stuff[89..93] probably doesn't do what you expect. It will return the first element of @stuff. My guess is that maybe you're trying to take elements 89, 90, 91, 92 of @stuff and assign them to ($a, $b, $c, $d). Is that right?

Taking into account what I've said, here's how I might rewrite your loop (by the way, what are you trying to do with this loop?):

my @fields; for (0..89) { my $field = $stuff[90]; print $field; push @fields, "$field\t"; }

Ta da! A loop that's easy to follow (but not very useful, it would seem...) Was that at all helpful?

-- Mike

--
XML::Simpler does not require XML::Parser or a SAX parser. It does require File::Slurp.
-- grantm, perldoc XML::Simpler

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://276821]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (7)
As of 2024-04-25 15:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found