7stud has asked for the wisdom of the Perl Monks concerning the following question:
Dear Monks,
A slice of an empty list is still an empty list. Thus: @a = ()[1,0]; # @a has no elements @b = (@a)[0,1]; # @b has no elements But: @a = (1)[1,0]; # @a has two elements @b = (1,undef)[1,0,2]; # @b has three elements More generally, a slice yields the empty list if it indexes only beyon +d the end of a list: @a = (1)[ 1,2]; # @a has no elements @b = (1)[0,1,2]; # @b has three elements
Why is indexing beyond the end of the list legal for a slice?
use strict; use warnings; use 5.014; use Data::Dumper; my %hash = ('hello', 1, 'goodbye', 2, 'world', 3, 'mars', 4); @hash{'goodbye', 'world'} = (); say Dumper(\%hash); --output:-- $VAR1 = { 'mars' => 4, 'hello' => 1, 'world' => undef, 'goodbye' => undef };
$VAR1 = { 'mars' => 4, 'hello' => 1, };
my @arr = (10, 20, 30, 40); @arr[1, 2] = (); say Dumper(\@arr); --output:-- $VAR1 = [ 10, undef, undef, 40 ];
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Array slices: beyond the end/ Assigning an empty list to a Hash slice
by kcott (Archbishop) on Mar 22, 2014 at 04:36 UTC | |
by 7stud (Deacon) on Mar 22, 2014 at 19:09 UTC | |
|
Re: Array slices: beyond the end/ Assigning an empty list to a Hash slice
by CountZero (Bishop) on Mar 22, 2014 at 12:54 UTC | |
by hazylife (Monk) on Mar 22, 2014 at 16:27 UTC | |
by CountZero (Bishop) on Mar 22, 2014 at 18:03 UTC | |
by 7stud (Deacon) on Mar 22, 2014 at 19:23 UTC | |
|
Re: Array slices: beyond the end/ Assigning an empty list to a Hash slice
by hazylife (Monk) on Mar 22, 2014 at 12:44 UTC |