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";
}
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.