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

Hi guys !

I stumbled a weired thing, and wondered if you can spread some light on this.
When I use: $#{$val} and $val is not an array, to my knowledge I'm supposed to get the value of -1.
when I did that, and the value of $val was the sign '+', I got the value of 1, and that quite of messed with my program coz' I expected to get the value of -1.
anyone can explain to me what happened here?

Thanks.

Hotshot
updated by boo_radley : Title Change
  • Comment on Odd behavior of non-array symbolic references with $# (was : array)

Replies are listed 'Best First'.
Re: array
by Sidhekin (Priest) on Apr 23, 2002 at 12:07 UTC

    Whether intentionally or not, you are using symbolic references. That is usually a bad idea, at least, as a certain monk will repeat, until and unless you know why it is (most often) a bad idea.

    What you are accessing is really $#+, which is the last index of @+, which perlvar says "holds the offsets of the ends of the last successful submatches in the currently active dynamic scope".

    ... which implies that this particular case will bite you only if there has been a successful match (with or without capturing braces, since the entire match is the 0th submatch) in the "currently active dynamic scope".

    I don't even want to know what the "currently active dynamic scope" is, and there are plenty other arrays always present, so I would try to rewrite that code not to use symbolic references. Try hashes, perhaps?

    The Sidhekin
    print "Just another Perl ${\(trickster and hacker)},"

Re: array
by ariels (Curate) on Apr 23, 2002 at 12:09 UTC
    If using v5.6.0 (or later), there are a built-in arrays named @- and @+ -- see perlvar (though it appears PM has older documentation than that).

    In any case, using symbolic references -- as you seem to be doing -- is not recommended, and prohibited under strict. Just so long as you know what you're doing...

Re: array
by derby (Abbot) on Apr 23, 2002 at 11:58 UTC
    More info is needed. On my system (RedHat 7.2, perl 5.6.1), $#val is -1.

    -derby

    Doh: @+ (which is what $#{$var} is when $var is '+') is a perl predefined var that contains offsets of successful matches. Do you have a regex before this code? Check out perlvar for more on @+

      I'm working with Red Hat 7.1 and perl 5.6.1

      Thanks.

      Hotshot