Perl: the Markov chain saw PerlMonks

### Re^2: \$# -variable?

by GrandFather (Saint)
 on Jul 27, 2006 at 09:15 UTC ( #563996=note: print w/replies, xml ) Need Help??

in reply to Re: \$# -variable?

Umm, not quite. Consider:

```use warnings;
use strict;

\$[ = 2;
my @array = ('a', 'b', 'c');

print "\$#array\n";

\$[ = 200;
print \$#array;

Prints:

```4
202

:)

DWIM is Perl's answer to Gödel

Replies are listed 'Best First'.
Re^3: \$# -variable?
by reneeb (Chaplain) on Jul 27, 2006 at 12:59 UTC
If someone plays with \$[, and you are using a loop as shown above, you have problems with both expressions \$#array and scalar(@array).

So, if you want to ensure that your loop does what you want, you have to use this one:

```#!/usr/bin/perl

use strict;
use warnings;

\$[ = 3;

my @array = qw(1 2 3 4);

for my \$i(\$[ .. \$[ + (scalar(@array) - 1) ){
print \$array[\$i],"\n";
}

or
```#!/usr/bin/perl

use strict;
use warnings;

\$[ = 3;

my @array = qw(1 2 3 4);

for my \$i(\$[ .. \$#array ){
print \$array[\$i],"\n";
}

I would hope these days that \$[ is virtually never used. I can imagine a few places where it may be tempting to use, but none where there are not much better techniques available.

\$['s biggest problem is the surprise factor. Non-zero based arrays are not the norm in Perl and using them is likely to make the code obscure and hard to maintain and its bigest weakness is that it provides nothing that cant be done better differently.

DWIM is Perl's answer to Gödel

Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://563996]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (2)
As of 2022-07-03 23:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?

No recent polls found

Notices?