in reply to $[ is under respected.

I have a hard time coming up for good reasons ever to change $[ from its default.

The only situation I can imagine, and it's a very farfetched one, is if I am translating from a non-zero-based indexing language (like Fortran) into Perl some extremely complex algorithm that I barely understand and that has lots of array index manipulations. In such a rare situation, for the sake of avoiding translation mistakes I may set $[ to 1. But even this would be temporary; ultimately, with a sufficiently solid test suite to back me up, I'd refactor the whole thing to 0-based indexing.

I'd be curious to know if any other monk has found any other use for a non-zero $[.

the lowliest monk

Replies are listed 'Best First'.
Re^2: $[ is under respected.
by Anonymous Monk on Aug 03, 2005 at 13:28 UTC
    Actually, your "far fetched" idea is close to the reason why Perl has $[. It's not so for porting non-Perl code to Perl, but for porting non-Perl programmers to Perl. In its early days, Perl didn't have many users, and it needed to recruit programmers who were familiar with other languages. Fortran for instance, but more likely, awk.

    I sometimes use $[. Whenever I find myself using -1 and +1 to switch to and from computer and human counting, I consider telling the computer to adapt to humans, and use $[. So instead of:

    for my $x (0 .. $X - 1) { for my $y (0 .. $Y - 1) { # Do something with $array[$x][$y] printf "bla, bla (%d, %d)", $x + 1, $y + 1; } }
    So I may write:
    { local $[ = 1; for my $x (1 .. $X) { for my $y (1 .. $Y) { # Do something with $array[$x][$y] print "bla, bla ($x, $y)"; } } }
Re^2: $[ is under respected.
by spiritway (Vicar) on Aug 05, 2005 at 03:19 UTC

    I was recently attempting to implement an algorithm for continued fractions, in which the subscript of the variables was negative. It occurred to me that it might be convenient to fudge the index to make the implementation easier for me.

    (Un)fortunately, I didn't know about $[, so I was compelled to actually understand the algorithm and write code so that Perl would be happy.

    I think this is something like the Perl philosophy, not constraining people to follow a particular path. It's nice to know I *could* move the index, if I wanted to - even though I understand that if I ever did that, I'd likely be sorry...

    A reply falls below the community's threshold of quality. You may see it by logging in.