Yes but ref aliasing doesn't allow slicing a subset out of it.
Yes, this is true. But earlier you said you would abstract it out into a function anyway, so it doesn't really matter how it's implemented ;-)
<update> See also </update>
use warnings;
use strict;
sub arr_alias_1 {
my ($arr,@i) = @_;
return sub {\@_}->(@$arr[@i]);
}
use Data::Alias 'alias';
sub arr_alias_2 {
my ($arr,@i) = @_;
alias my @x = @$arr[@i];
return \@x;
}
sub arr_alias_3 {
my ($arr,@i) = @_;
use 5.022; # for refaliasing
use experimental 'refaliasing';
my @x;
#(\@x) = \(@$arr[@i]); # Assigned value is not an ARRAY reference
#\@x[0..$#i] = \(@$arr[@i]); # @x is just undefs?
\$x[@x] = \$$arr[$_] for @i; # works
return \@x;
}
sub hash_alias_1 {
my ($hash,@k) = @_;
... # not possible in pure Perl?
}
use Data::Alias 'alias';
sub hash_alias_2 {
my ($hash,@k) = @_;
use 5.020; # for Key/Value Hash Slices
alias my %x = %$hash{@k};
return \%x;
}
sub hash_alias_3 {
my ($hash,@k) = @_;
use 5.022; # for refaliasing
use experimental 'refaliasing';
my %x;
#\(@x{@k}) = \(@$hash{@k}); # values of %x are undefs?
\$x{$_} = \$$hash{$_} for @k; # works
return \%x;
}
# arr_alias_4 and hash_alias_4 could be implemented with "tie"...
use Test::More tests=>10;
for my $aa (\&arr_alias_1,\&arr_alias_2,\&arr_alias_3) {
my @arr = ('a'..'z');
my $subset = $aa->(\@arr, 5..10);
is_deeply $subset, ['f'..'k'] or diag explain $subset;
$subset->[3] = 9;
is_deeply \@arr, ['a'..'h',9,'j'..'z'];
}
for my $ha (\&hash_alias_2,\&hash_alias_3) {
my %hash = map {$_=>uc} 'a'..'z';
my $subset = $ha->(\%hash, 'f'..'k');
is_deeply $subset, { map {$_=>uc} 'f'..'k' }
or diag explain $subset;
$subset->{i} = 9;
is_deeply \%hash, { i=>9, map {$_=>uc} 'a'..'h','j'..'z' };
}
|