in reply to WWW::Mechanize and following multiple links

This is unrelated to Mech, but it makes me terribly nervous to see people using $_ for loops of more than one line. You're playing with a global variable, and I sure hope nothing stomps on it. It's trivial to change that to
for my $i ( 0..9 ) { blah blah $link[$i]->whatever; }
and now you're not going to have something somewhere else modify $_ when you're not expecting it.

xoxo,
Andy

Replies are listed 'Best First'.
Re^2: WWW::Mechanize and following multiple links
by bart (Canon) on Nov 25, 2004 at 01:26 UTC
    I might get nervous, but not extremely nervous. Subs (and methods) shouldn't clobber $_ unless they're documented to — and with a purpose. For every line in your block it should be clear to what exactly it does to $_.

    In such a case, multiline blocks using $_ are fine.

    p.s. Your anxiousity doesn't warrant to be restricted to just for loops. You seem to be wary of anything messing with $_, anywhere. Probably you never use $_ over several lines.

Re^2: WWW::Mechanize and following multiple links
by Limbic~Region (Chancellor) on Nov 25, 2004 at 01:26 UTC
    petdance,
    I tend to pay close attention to people who have had a fair amount of experience. When I first read what you wrote, I got a little nervous because I often use foreach loops without specifying a looping variable. I thought about it a bit, and just about everything in perl that sets $_ localizes it first like map, grep, foreach loops, etc (while loops excluded). I didn't do an exhaustive search (checked the CB) but the list was quite short of things that I found that modify $_:
    • chomp
    • chop
    • s///
    Since $_ is aliased, I am intentionally changing $_ if I use one of those. Am I completely missing the boat here? I am not saying there isn't any case where this can't bite you but is it more common than I think or are you just protecting against Murphy's Law?

    Cheers - L~R

      Those while loops that you are excluding are the primary danger here; the problem scenario usually manifests something like:
      sub foo { while (<$fh>) { ... } } for (@important) { ... foo(); ... }
      and presto, elements in @important are replaced by lines from $fh.
Re^2: WWW::Mechanize and following multiple links
by diotalevi (Canon) on Nov 25, 2004 at 02:33 UTC

    Andy,
    Is it ok to dclone a WWW::Mechanize object to avoid having to deal with ->back? If so, could you add that or a similarly functioning method to the distribution? That'd sure make my life easier.

      I'm not sure what exactly you're wanting to do, but submit a request with a patch, or at least sample code that you imagine it to be, to bug-www-mechanize@rt.cpan.rog.

      xoxo,
      Andy