Arrays and negative indexes in Perl

前端 未结 3 1610
北荒
北荒 2021-01-12 17:48

I am newbie in Perl and I am reading about arrays.
As I understand the arrays expand automatically as needed (cool!)
But I also read that we can use neg

3条回答
  •  清酒与你
    2021-01-12 18:15

    You get an undef value if You read the value.

    use strict;
    use warnings;
    
    my @l = qw(A B C);
    print $l[-4];
    

    Output to stderr (program continues to run):

    Use of uninitialized value in print at ./x.pl line 7.
    

    Or:

    my @l = qw(A B C);
    print "undef" if !defined $l[-4];
    

    Output:

    undef
    

    If You want to assign a value to it You get an error:

    my @l = qw(A B C);
    $l[-4] = "d";
    

    Output (program exits):

    Modification of non-creatable array value attempted, subscript -4 at ./x.pl line 7.
    

    And actually the interval can be modified. So an array can start any value not only 0.

    my @l = qw(A B C);
    $[ = -4; # !!! Deprecated
    print $l[-4], "\n";
    print $l[-3], "\n";
    

    Output:

    A
    B
    

提交回复
热议问题