>>>>> "BRH" == Bryan R Harris <bryan_r_har...@raytheon.com> writes:

  >>>>>>> "BRH" == Bryan R Harris <bryan_r_har...@raytheon.com> writes:

  >> how would that work any better as $_ is still set to each element?

  BRH> Because somehow the $_ is localized with foreach where it is not with the
  BRH> implicit (?) while loop.

foreach always localizes its iterator unless it was declared
lexical. while doesn't have an iterator as it only does a boolean check
of its condition. the trick of adding defined() around a <> does not
know if $_ or a lexical is used there as it doesn't know anything about
the code. it just recognizes <> and assignments from it.

  BRH> My question is:  why?  Seems like such an easy thing to have done.
  >> 
  >> it would be better for you to use lexical vars then you wouldn't need to
  >> worry about action at a distance with $_. also the code reads better as
  >> you know what you are working with instead of the generic $_. this are two
  >> of the reasons why i always teach to avoid $_ in most code. use it where
  >> you must (grep, map, foreach modifier) or where it really helps out the
  >> code. for line loops, it doesn't help at all so avoid it. and lexicals
  >> are safer and if well named, better for maintaining the code.

  BRH> I actually love using $_.  It saves all kinds of typing when doing lots 
of
  BRH> regex'ing, e.g.:

  BRH> while(<FILE>) {
  BRH>     s/^\s*#.+//;
  BRH>     s/\^/**/g;
  BRH>     s/(\d)e(\d)/$1E$2/g;

that is ok in some cases. it gets annoying if too much is done that
way. i like to know what you are modifying and not having to keep
looking up where $_ is assigned (implicitly above). the concept of
keeping information tightly scoped also applies here. 

  BRH>     if (!/\S/) { push @lines, $_; }

  BRH> }

  BRH> I don't see why it "doesn't help at all" in these kinds of loops.

because you don't have a name where you could have a name. names are the
most important human aspect of coding. the computer cares not about
names but the readers of your code do. so having the ability to pick
names and actually picking good ones is a great
responsibility. defaulting to $_ seems cool and shorter to you but it
can be uncool and obscure to others. also it keeps you from ever having
this action at a distance that you just had. why risk shooting yourself
in the foot? i sure like having no holes in my feet.

uri

-- 
Uri Guttman  ------  u...@stemsystems.com  --------  http://www.sysarch.com --
-----  Perl Code Review , Architecture, Development, Training, Support ------
---------  Gourmet Hot Cocoa Mix  ----  http://bestfriendscocoa.com ---------

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to