Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: why need my in a foreach loop?

by moritz (Cardinal)
on Nov 28, 2010 at 07:47 UTC ( #874081=note: print w/ replies, xml ) Need Help??


in reply to why need my in a foreach loop?

use strict 'vars' basically says "all variables that you use must be declared (unless they contain :: or ').

Using a variable in a loop is not different from using a variable in an assignment: it can either use an existing one, or it can be a fresh one, declared with my.

Or put another way: use strict; forces you to be explicit about your declarations. Having some construct doing implicit declarations, at least in some circumstances, goes against the entire idea of strict.

Update: Perl 6 gets around this by having other declarative syntax forms. Signatures can be used for that, either by being attached to a routine, or in the form of a lambda:

# | declares $x in the scope of the block my $lambda = -> $x { $x * $x } # reused in loop syntax: for <a b cd> -> $x { say $x } # | declares $x in the scope of the block sub square($x) { $x * $x }


Comment on Re: why need my in a foreach loop?
Select or Download Code
Re^2: why need my in a foreach loop?
by szabgab (Priest) on Nov 28, 2010 at 18:33 UTC
    apparently most people thought here I don't understand that use strict (or more specifically the 'vars' part of it) forces the need of "my". My question why do we need that in a for-loop.

    As you also know way better than I, Perl 6 can get by without this. I don't see when does that "my" do any useful work there. It is not the "my" that defines the scope of this variable so IMHO it is there only to satisfy "use strict".

      I love that in Perl6 loops automatically create localized variables: (may look familiar to Gabor)

      for @names -> $n { say $n; }

      Why not backport that feature into Perl5. Maybe only if warnings and strict and features are full on.<?p>

      As Occam said: Entia non sunt multiplicanda praeter necessitatem.

      It is not the "my" that defines the scope of this variable so IMHO it is there only to satisfy "use strict".

      I can't think of any other cases in which Perl 5 automatically lexicalizes a named variable without my; I think it's a (useful) consistency.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (4)
As of 2014-09-16 04:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite cookbook is:










    Results (155 votes), past polls