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";
}
-
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.
|