Preserve aliasing with Map

C

ctcgag

I had a script whose inner workings (greatly simplified) worked like this:

foreach my $r (@record) {
my @codes=something($r);
foreach my $entry ( grep foo($_), @entry_hash{@codes} ) {
next unless defined $entry;
## do some stuff here
undef $entry;
};
}

Since a hash slice gives L-values, and since both grep and foreach do
aliasing, the last line of the inner loop actually changed each value (in
%entry_hash) on which it did work, so that later I could figure out if any
thing in %entry_hash were "orphans" that didn't get operated on.

Later, I needed to change it so that each slot in %entry_hash held a list
of entries, rather than one entry. But this code:

foreach my $r (@record) {
my @codes=something($r);
foreach my $entry ( grep foo($_), map {$_?@$_:()} @entry_hash{@codes} ) {
next unless defined $entry;
## do some stuff here
undef $entry;
};
}

Did not work, because the map broke the aliasing chain and so the change to
$entry would not be reflected in the original data structure. I ended up
adding an extra foreach loop between the inner and outer ones, but I wonder
of there was a more elegant way to preserve the aliasing chain.

Thanks,

Xho
 
B

Brian McCauley

I had a script whose inner workings (greatly simplified) worked like this:
foreach my $entry ( grep foo($_), @entry_hash{@codes} ) {
Later, I needed to change it so that each slot in %entry_hash held a list
of entries, rather than one entry. But this code:
foreach my $entry ( grep foo($_), map {$_?@$_:()} @entry_hash{@codes} ) {
Did not work, because the map broke the aliasing chain and so the change to
$entry would not be reflected in the original data structure.

This is a problem I've encountered a number of times.
I ended up adding an extra foreach loop

That's what I usually do.
but I wonder of there was a more elegant way to preserve the
aliasing chain.

You could switch to using references.

foreach my $entry ( grep foo($$_), map {$_ ? \(@$_) : () } @entry_hash{@codes} ) {

Now a change to $$entry will be reflected in the original data structure.

--
\\ ( )
. _\\__[oo
.__/ \\ /\@
. l___\\
# ll l\\
###LL LL\\
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,135
Latest member
VeronaShap
Top