Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: Lexical closures

by chromis (Novice)
on Oct 27, 2008 at 20:09 UTC ( [id://719824]=note: print w/replies, xml ) Need Help??


in reply to Lexical closures

Hello,

This is my first post ;)

Perhaps this snippet of code is also convenient for a better understanding. I always like to print references in order to understand such things:

#!/usr/bin/perl use strict; use warnings; use feature qw/say/; my @array = (1, 2, 4, 8, 16, 32, 64, 128); foreach my $elem (@array) { say \$elem; # this *doesn't* print a unique number for all iterati +ons! $elem *= 2; } say join(', ', @array); say join(', ', map(\$_, @array)); # ..surprisingly familiar! @array = qw/x y z/; say join(', ', @array); say join(', ', map(\$_, @array)); # ..surprisingly familiar too! say \@array[0];
The output at my machine is:
SCALAR(0x8153220) SCALAR(0x8153360) SCALAR(0x8153100) SCALAR(0x817bcb8) SCALAR(0x817bcc8) SCALAR(0x818ea18) SCALAR(0x81886d0) SCALAR(0x8188fd0) 2, 4, 8, 16, 32, 64, 128, 256 SCALAR(0x8153220), SCALAR(0x8153360), SCALAR(0x8153100), SCALAR(0x817b +cb8), SCALAR(0x817bcc8), SCALAR(0x818ea18), SCALAR(0x81886d0), SCALAR +(0x8188fd0) x, y, z SCALAR(0x8153220), SCALAR(0x8153360), SCALAR(0x8153100) SCALAR(0x8153220)
edit: this may also be of interest
my $i = 123; say $i . ' ' . \$i; foreach $i (1 .. 3) { say $i . ' ' . \$i; } say $i . ' ' . \$i;
output:
123 SCALAR(0x817bd18) 1 SCALAR(0x8153220) 2 SCALAR(0x8153220) 3 SCALAR(0x8153220) 123 SCALAR(0x817bd18)
The reason why the scalars are the same inside the foreach in this particular occasion is because I'm now iterating over a list and not an array. I've always assumed that there is a difference, and that lists only exist in Perl source code and that they are solely used for initialization of other things such as arrays (and hashes). Is this correct?

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (7)
As of 2024-04-18 11:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found