Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Does a foreach create a scalar reference?

by hesco (Deacon)
on May 26, 2009 at 19:07 UTC ( [id://766278]=perlquestion: print w/replies, xml ) Need Help??

hesco has asked for the wisdom of the Perl Monks concerning the following question:

This works, I just don't understand why. Can anyone please shed some light on why my timestamp elements are affected by my assignment to a locally scoped variable in a while loop? Does this foreach construct make $element a reference to the underlying list element?

-- Hugh

#!/usr/bin/perl -w use strict; use warnings; my ($s,$m,$h,$dy,$mo,$yr,$t1,$t2,$t3) = localtime; $mo++; $yr += 1900; foreach my $element ($s,$m,$h,$dy,$mo){ $element = '0' . $element if(length($element) < 2); print $element, "\n"; } print <<EndOfString; $yr-$mo-$dy $h:$m EndOfString
This produced output looking like this:

49 54 14 26 05 2009-05-26 14:54
if( $lal && $lol ) { $life++; }

Replies are listed 'Best First'.
Re: Does a foreach create a scalar reference?
by DStaal (Chaplain) on May 26, 2009 at 19:19 UTC

    From Perlsyn

    In other words, the foreach loop index variable is an implicit alias for each item in the list that you're looping over.

    In other words: Yes. It creates a reference.

    On a side note: I'm glad to see use strict; and use warnings, but you don't need #!/usr/bin/perl -w as well: The -w is basically a slightly dumbed-down version of use warnings, and is redundant in this code. (And unless you understand why I said 'in this code', is likely to cause you headaches someplace down the line if you keep using it.)

Re: Does a foreach create a scalar reference?
by jwkrahn (Abbot) on May 26, 2009 at 19:29 UTC

    This behaviour is described in the third paragraph of the Foreach Loops section of the perlsyn document.

    But perhaps it would be simpler to use sprintf to add leading zeros to your numeric fields:

    my ( undef, $m, $h, $dy, $mo, $yr ) = localtime; print sprintf "%d-%02d-%02d %02d:%02d\n", $yr + 1900, $mo + 1, $dy, $h +, $m;

      Or even cleaner just let strftime do the grunt work for you.

      The cake is a lie.
      The cake is a lie.
      The cake is a lie.

Re: Does a foreach create a scalar reference?
by shmem (Chancellor) on May 26, 2009 at 19:57 UTC
    Does this foreach construct make $element a reference to the underlying list element?

    Yes, it does.

Log In?
Username:
Password:

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

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

    No recent polls found