http://qs1969.pair.com?node_id=210487

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

I was playing with tied arrays when I found a strange behaviour. I tried the code (which you can see below) both with Perl 5.6.0 and with 5.8.0 on my MacOS X box, and it runs without surprises. With ActiveState 5.6.1 build 633, though, it leads to the following problem: if I use print $_; print "\n" to print the values, the program's output is:
Now I'm fetching the element with index: 0
Perl
Now I'm fetching the element with index: 1
Monks
On the other hand, if I use print "$_\n" the output is:
Now I'm fetching the element with index: 0
Now I'm fetching the element with index: 0
Perl
Now I'm fetching the element with index: 1
Now I'm fetching the element with index: 1
Monks
So, it seems it enters the sub FETCH twice, when I use $_ in a string. As I already said, the behaviour is the same (the first one behaviour, to be clear), when I try the code with different versions of Perl on MacOS X. Now, the code:
#!/usr/bin/perl use strict; use warnings; package Dummy; sub TIEARRAY { my $class = shift; return bless [], $class; } sub STORE { my $self = shift; my $index = shift; my $value = shift; return ($self->[ $index ] = $value ); } sub FETCH { my $self = shift; my $index = shift; print STDERR "Now I'm fetching the element with index: $index\n"; return $self->[ $index ]; } sub FETCHSIZE { my $self = shift; return scalar( @$self ); } package main; my @array; tie @array, 'Dummy'; $array[0] = 'Perl'; $array[1] = 'Monks'; foreach ( @array ) { print "$_\n"; # print $_; print "\n"; }