[Melbourne-pm] Perl chop behaviour

Sisyphus sisyphus1 at optusnet.com.au
Sun Aug 14 05:37:37 PDT 2005


----- Original Message ----- 
From: "Becky Alcorn"
>
> That makes some sense.  My only problem with this of course is that before
> the chop I had a functioning array and after the chop I don't.

You still have a functioning array after the chop - but it's considered to
be only one dimensional. The error you see is the error you get when you try
to treat any 1D array as multidimensional:

use strict;
use warnings;

my @r = ('jim', 'bob' );
print $r[0][1], "\n";
__END__

In the code you provided below, the second call to Dumper() still works if
you remove the attempts to print $array[2][0] and $array[2][1].

> #!/usr/bin/perl
> use strict;
> use warnings;
> use Data::Dumper;
>
> my @array = (
>   'fred',
>   'jill',
>   ['aa', 'bb'],
> );
>
> print "1: $array[0]\n";
> print "2: $array[1]\n";
> print "3: $array[2]\n";
> print "3a: $array[2][0]\n";
> print "3b: $array[2][1]\n";
>
> print Dumper(\@array) . "\n";
>
> chop(@array);
>
> print "1: $array[0]\n";
> print "2: $array[1]\n";
> print "3: $array[2]\n";
> print "3a: $array[2][0]\n";
> print "3b: $array[2][1]\n";
>
> print Dumper(\@array) . "\n";

This "feature" can be reduced to:

use strict;
use warnings;

my $ref = [ 'jim', 'bob' ];
chop($ref);
print "@$ref\n";
__END__

I think you're right, btw - in that perl should refuse/ignore instructions
to chop references.
A (fatal) refusal is what you get if you try:

use strict;
use warnings;

my @r = ('jim', 'bob');
chop(\@r);
print "@r\n";
__END__

It doesn't even compile (irrespective of strictures) - and I think it's
inconsistent that perl *does* compile the code you provided.

Cheers,
Rob







More information about the Melbourne-pm mailing list