Reference Tricks With Grep and Map
#!/usr/bin/perl -w
################### Reference Tricks With Grep and Map ######################
$rLoL = [[20,30], [40,50,60], [10]]; # Reference to List of List
## Converting $rLoL into a simple one dimensional list
@NormalList = map {@$_} @$rLoL; # $_ is a list REFERENCE!
print "@NormalList\n";
## "Deep Copying" (cloning) $rLoL into another reference.
@$rClone = map {[@$_]} @$rLoL; # Expand $_'s array into a NEW ADDRESS!
$rLoL->[1][1] = 95;
foreach $ref (@$rClone) {print "@$ref\n"} # Clone should NOT have the 95 in it!
foreach $ref (@$rLoL) {print "@$ref\n"}
## Removing lists from a list of lists by a certain criterion.
@$rLoL = grep {@$_ >= 2} @$rLoL; # Lists of size 1 or 0 should disappear!
foreach $ref (@$rLoL) {print "@$ref\n"}
## "Deep Copying" (cloning) a List of Hash.
@LoH = ({"a" => 1, "b" => 4}, {"c" => 2}, {"a" => 6, "b" => 5, "d" => 7});
@NewLoH = map {{%$_}} @LoH; # Expand $_ inside new hash address braces
foreach $href (@NewLoH) { # Do a dump to see if the cloning worked.
foreach $key (sort keys %$href)
{
print "$key $href->{$key} ";
}
print "\n";
}
## Case Study: Keeping lists that have at least one score above some value.
$value = 75;
$rLoL = [[78,43,87], [64,73,72], [99], [65,67,71]];
@$rLoL = grep {(grep {$_ > $value} @$_) >= 1} @$rLoL; # Inside grep is SCALAR!
foreach $ref (@$rLoL) {print "@$ref\n"} # Should keep only 1st and 3rd list.
## Case Study: Dereferencing one row of a list of lists.
$rLoL = [[1,2], [3,4], [5,6], [7,8]];
print "@{$rLoL->[2]}\n"; # Prints 5 6. When you deref. a name with a
# subscript, the deref must be surrounded by {}.
################################ Program Output #############################
20 30 40 50 60 10 # One dimensional array after 2-D array was "flattened".
20 30 # Rows of the clone of original @$rLoL
40 50 60
10
20 30 # Rows of the original @$rLoL after $rLoL->[1][1] changed to 95.
40 95 60
10
20 30 # Two rows of @$rLoL left after grep removed the list of size ONE.
40 95 60
a 1 b 4 # One hash dumped per line.
c 2
a 6 b 5 d 7
78 43 87 # Notice that these lists have at least ONE value above 75!
99
5 6 # Results of dereferencing one row of a referenced list of lists.