Hello Monks,
I am trying to enlighten myself by reading as much code on here as possible and figuring out the parts that I do not understand. I came across this post
Networking Perl today and
Your Mother's reply had the following code
use warnings;
use strict;
use JSON;
use Plack::Request;
use Proc::ProcessTable;
sub {
my $req = Plack::Request->new(+shift);
my %pids = map { $_ => 1 } $req->path =~ /(\d+)/g;
my $procs = Proc::ProcessTable->new;
my $json = JSON->new;
my %status;
for my $proc ( @{ $procs->table } )
{
next if scalar(%pids) and not $pids{$proc->pid};
for my $field ( $procs->fields )
{
$status{$proc->pid}{$field} = $proc->$field;
}
}
return [ 200,
[ "Content-Type" => "application/json" ],
[ $json->pretty->encode(\%status) ]
];
};
There are two items in this that are giving me trouble. First this map, I don't quite understand what it is doing (it seems no matter how much I read about map I still can't quite grasp it):
my %pids = map { $_ => 1 } $req->path =~ /(\d+)/g;
Is it saying "For each item found in $req->path that is a number save it as a hash key of %pids?"
The other thing that confuses me is this
next if scalar(%pids) and not $pids{$proc->pid};
I know "scalar(%pids)" will force the hash %pids to be interpreted in scalar context, but to be honest with you I do not know exactly what this will do to the hash. I tried testing this on my own with the following code:
my %hash = (
fred => flintstone,
wilma => flintstone,
barney => ruble,
);
print scalar(%hash) . "\n";
But this prints out "3/8" so I'm really confused.
Thank you for helping me on my journey.
Thanks,
Dru
Perl, the Leatherman of Programming languages. -
qazwart