Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re^2: Huge simple problem

by dsheroh (Monsignor)
on Aug 06, 2009 at 00:04 UTC ( [id://786253]=note: print w/replies, xml ) Need Help??


in reply to Re: Huge simple problem
in thread Huge simple problem

May I suggest that you learn to use the foreach loop in Perl, rather than the c-style for loop.

Do note that foreach is just an alternate spelling of for. for my $text (@searchtexts) { ... } is exactly equivalent to foreach my $text (@searchtexts) { ... }.

Either way, though, I can't remember the last time I used a C-style for loop in Perl. for ( [list] ) is so much nicer and avoids all those nasty off-by-one errors.

Replies are listed 'Best First'.
Re^3: Huge simple problem
by Anonymous Monk on Aug 06, 2009 at 01:00 UTC

    I second this advice, and (missingthepoint posting anonymously), ++ to you both for helpful replies (when I remember what I changed my password to).

    Also, may I suggest you use strict and use warnings? (put those two lines at the top of your code). It will save you a lot of time - I speak from painful experience :|

    One final word: it appears as though you're trying to get the number of elements in @a by writing @a +1 -1. That's contorted - you can just say $i <= @a, since <= puts its operands (that is, $i and @a) in scalar context, and for the array, produces the number of elements it contains.

    You can improve that even further, too. As it stands you have an off-by-one error - looping from $i = 0 to $i = @array<c> will put you one element beyond the end. If you need a C-style for loop, you can write: <c>for ($i = 0; $i < @a; $i++) { ... and be done with it. :)

    But in your situation, you would be better served just doing what dsheroh++ said and using a plain for: for my $element (@a) { <do something with element> ...

    Don't hesitate to let me know if that was unclear. :)

      ... and you already noticed (part of) that. Never mind, hopefully someone else benefits from that node.
Re^3: Huge simple problem
by dreadpiratepeter (Priest) on Aug 06, 2009 at 04:07 UTC
    I always say foreach when doing (@a) type loops and for when doing c-style loops. helps make the code a little more self-documenting


    -pete
    "Worry is like a rocking chair. It gives you something to do, but it doesn't get you anywhere."

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (6)
As of 2024-04-20 00:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found