Perl Christmas Quiz 2009
Dave Cross
dave at dave.org.uk
Tue Dec 1 17:11:36 GMT 2009
On 12/01/2009 04:52 PM, Dermot wrote:
> 2009/12/1 Matt Sergeant<msergeant at messagelabs.com>:
>> On Tue, 1 Dec 2009 11:23:09 -0500, Matt Sergeant wrote:
>>> On Mon, 30 Nov 2009 18:24:12 +0000, Chris Jack wrote:
>>>> 1) Without running it to check, what does the following program output?
>>>>
>>>>
>>>> my %a = (3,2,1,0);
>>>>
>>>>
>>>> for my $b (sort values %a) {
>>>> $b += 4;
>>>> }
>>>>
>>>>
>>>> print $a{1} . "\n";
>>>
>>> Bizarrely enough, on both my Snow Leopard machines (default perl
>>> install) this outputs: 4D
>
> This is one of those situation where I should keep quiet to avoid
> showing my ignorance but I can't help myself.
>
> My first impression was that it would be 4. However, without running
> it, I would say 0 on the basis that $b is scoped within the loop and
> (not sure about this point) is a copy of the value in $a{1}.
Ah, but $b isn't a copy (of the value in) $a{1}, it's actually an
_alias_ to the value in $a{1}. Updating $b will change the value in the
underlying hash.
Same thing applies in a foreach loop (and probably other places).
foreach my $foo (@bar) {
# Updating $foo changes the value in @bar
}
> I await the flak.
No flak. It's a common enough misunderstanding. Happy to have the chance
to explain.
Dave...
More information about the london.pm
mailing list