my %distAvail;
foreach (map(split(/\D+/,$_),<STDIN>)) { $distAvail{$_ }++; };

What does $distAvail{$_ }++; mean here?
The input is set of distances separated by whitespace (or any non-digit character). The book says %distAvail keys are distances and whose values give the number of copies of the key. But I don't understand how $distAvail{$_ }++;works.More over I have read that systax of map is
map EXPR, LIST;
but <STDIN> is not a list(i.e array) but a string of distances. Please correct me.

If you'll notice, $_ in the hash is inside the foreach loop, meaning that it refers to that individual value for that iteration of the loop, or a single value resulting from the split of "string of distances" making it refer to a single distance.

Yes I know that split(/\D+/,$_) splits the entered distance into individual values. But I don't understand the complete statement foreach (map(split(/\D+/,$_),<STDIN>)) { $distAvail{$_ }++; };

Like I said, the foreach splits the input line, so now you do have a list of distances. The body of the foreach (the part between the braces) then uses each of these distances, one at time, as a key in the hash and increments the value at that position. If you know that the first part splits the line into individual distances, and you know what a hash is, and you know what foreach is, then I don't understand what it is you don't understand about that line.

I am sorry if I appear so silly, I am just a newbie in Perl. I don't understand how the map function is working here and giving the results that you said. Actually map function is used differently here that I have read before.
Here it is taking a single string (input) i.e. a scalar and splitting it with split function into different distances.
More over don't we need to initialize the values of hash before increment as in C++. Or it takes automatically the initial value 0. Ok I am checking it now. Thanks for replying.

ya..

my $key;
$key++;
print $key;

The output is 1. So, perhaps perl is initializing automatically as 0
Thanks again.. I am also making a note of using map in this way.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.