G'day 7stud,
"1) From perldata/Slices: ... Why is indexing beyond the end of the list legal for a slice?"
Your question here seems to imply an assumption.
This might be:
"Why is indexing beyond the end of the list legal for a slice when it's illegal for an array?"
which would be a false assumption.
You may want to correct or clarify that; however, in case that is the assumption you're making, consider this code:
#!/usr/bin/env perl -l
use strict;
use warnings;
print '*** Create @x with no elements ***';
my @x;
print 'Elements in @x: ', scalar @x;
print '*** Use array index beyond end as RHS of assignment ***';
my $y = $x[42];
print 'Value assigned from beyond end of @x: ', defined $y ? $y : '<un
+def>';
print 'Elements in @x: ', scalar @x;
print '*** Use array index beyond end as LHS of assignment ***';
$x[21] = 'hello';
for my $i (0, 10, 21, 32) {
print "Index: $i";
print 'Value: ', defined $x[$i] ? $x[$i] : '<undef>';
}
print 'Elements in @x: ', scalar @x;
Output:
*** Create @x with no elements ***
Elements in @x: 0
*** Use array index beyond end as RHS of assignment ***
Value assigned from beyond end of @x: <undef>
Elements in @x: 0
*** Use array index beyond end as LHS of assignment ***
Index: 0
Value: <undef>
Index: 10
Value: <undef>
Index: 21
Value: hello
Index: 32
Value: <undef>
Elements in @x: 22
"2) I think the slice docs should mention the case when you assign an empty list to a hash slice, like this:"
I can't find any specific mention of that in perldata.
Someone else may be able to point you to another manual page that does explain this.
In any event, you can always use perlbug to request changes or additions to documentation.
"It's not obvious(to me at least) why the value undef gets assigned to the sliced keys. It seems to me that the hash could just as well look like:"
Instead of the hash slice assignment:
@hash{'goodbye', 'world'} = ();
Consider the individual assignments to each key:
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Dumper;
my %hash = ('hello', 1, 'goodbye', 2, 'world', 3, 'mars', 4);
print Dumper \%hash;
$hash{goodbye} = ()[0];
$hash{world} = ()[1];
print Dumper \%hash;
Output:
$VAR1 = {
'hello' => 1,
'goodbye' => 2,
'world' => 3,
'mars' => 4
};
$VAR1 = {
'hello' => 1,
'goodbye' => undef,
'world' => undef,
'mars' => 4
};
That may help in understanding what is going on when an empty list is assigned to a hash slice.
Here's a further example where the list being assigned has less elements than the hash slice has keys:
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Dumper;
my %hash = ('hello', 1, 'goodbye', 2, 'world', 3, 'mars', 4);
print Dumper \%hash;
@hash{'goodbye', 'world'} = ('farewell');
print Dumper \%hash;
Output:
$VAR1 = {
'hello' => 1,
'goodbye' => 2,
'world' => 3,
'mars' => 4
};
$VAR1 = {
'hello' => 1,
'goodbye' => 'farewell',
'world' => undef,
'mars' => 4
};
|