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

Hi fellow monks.. ;).

Sorry to disturb you from your daily routines (hacking? ;J), but I can't seem to figure this out. What evil do special characters inflict on Perl arrays? Basically, I have pushed a piece of text containing special (control) characters '\cJ ...' and when I check on last array index via '$#' i get 10 whereas it should be 1 (since I know i added just that one string).

Here's a 'screenshot' from command line perl debugger:
CFML::Parser::TAG::Container::owner_of(/export/home/vlad/scratch/LIB/C +FML/Parser.pm:792): 792: $self->{op_stack}[++$#self->{op_stack}] = $t +hing; DB<1> x $self->{op_stack} 0 ARRAY(0x3f513c) 0 "\cJ\cI " DB<2> x $#self->{op_stack} 0 10 DB<3>
Why does it show 10 there when i do $#self->{op_stack}.? Should it not display '0' since that's the last index of the array as seen in earlier dump of that array via 'x' command?

Thank you. </code>

"There is no system but GNU, and Linux is one of its kernels." -- Confession of Faith

Replies are listed 'Best First'.
(Ovid) Re: Special characters in array
by Ovid (Cardinal) on Dec 27, 2001 at 00:56 UTC

    That works because you're not using strict and Perl is treating $#self->{op_stack} as if $self is an array reference. With strict, you would have been told that "Global symbol @self" requires an explicit package name at ...". That should have given you the information that you need to tweak the script a little.

    $#{ $self->{ op_stack } }

    This snippet will show you more:

    package Foo; use strict; sub new { my $class = shift; my $stuff = { a => [ qw/ Ovid is a schmuck / ] }; bless $stuff, $class; return $stuff; } package main; use base "Foo"; my $test = Foo->new; use Data::Dumper; print Dumper $test; print $#{$test->{a}};

    That prints '3', like it should.

    Cheers,
    Ovid

    Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.

Re: Special characters in array
by chip (Curate) on Dec 27, 2001 at 02:12 UTC
    In addition to Ovid's excellent reply, I would add that the idiom $array[++$#array] is extraordinarily silly. That's what the push operator does, only it's faster and more readable.

        -- Chip Salzenberg, Free-Floating Agent of Chaos