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?
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.