in reply to Help me decipher code containing map function
For better readability of the code, how can I rename the $_ variable.
Well, one way might be with English:
my @x = map {$_*2} 1..3; # --becomes--> use English; my @y = map { $ARG * 2 } 1..3;
But I think the point of map and $_ is to be relatively short, so if you want to improve readability by being a bit more verbose, the general pattern for that is:
my @x = map {sprintf("%02x",$_)} 45..48; # --becomes--> my @y; for (45..48) { push @y, sprintf("%02x",$_); } # --becomes--> my @z; for my $val ( 45 .. 48 ) { push @z, sprintf "%02x", $val; }
I would rather know step by step exactly what the code is doing ... I do not see the above code having a list passed to it.
Here are two debugging techniques to help with that: First, Data::Dump (like Data::Dumper but with a bit nicer output), for example:
use Data::Dump; dd( unpack "CCCCCC", "\xab\xcd\x00\x1d\x94\x56" ); __END__ (171, 205, 0, 29, 148, 86)
So you see that unpack is returning a list. Second, if you're unsure what context a function is being called in, like localtime(time) in the following example, then to test it you can replace the function call with the whatcontext function I show below, which makes use of wantarray.
my $q = localtime(time); my ($r) = localtime(time); sub whatcontext { print wantarray ? "list" : defined wantarray ? "scalar" : "void", "\n"; return; } my $s = whatcontext; my ($t) = whatcontext; whatcontext; __END__ scalar list void
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Help me decipher code containing map function
by adamZ88 (Beadle) on May 23, 2017 at 14:54 UTC |