Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

Re: Lexical closures

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

in reply to Lexical closures


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;
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?

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

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (5)
As of 2019-07-18 19:27 GMT
Find Nodes?
    Voting Booth?

    No recent polls found