Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: Help me decipher code containing map function

by haukex (Archbishop)
on May 20, 2017 at 07:56 UTC ( [id://1190701]=note: print w/replies, xml ) Need Help??


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

    Thank you for explaining that renaming the $_ would defeat the purpose of the map function to an extent. Additional, thank you for providing me for more tools to achieve my goals!

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1190701]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (4)
As of 2024-11-05 02:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    chatterbot is...






    Results (27 votes). Check out past polls.