Operating System - Linux
1821051 Members
2746 Online
109631 Solutions
New Discussion юеВ

help me understand this perl one liner

 
SOLVED
Go to solution
Abdul khadeer_1
Occasional Advisor

help me understand this perl one liner

Hi,
in this thread
http://forums1.itrc.hp.com/service/forums/questionanswer.do?threadId=1065208
i saw the solution to problem as
#perl -ne '($h,$n)=split; if ($old=$o{$h}) {print "$h : ", $n - $old, "\n"} else {$o{$h}=$n}' file1.txt file2.txt
what does $h,$n where does the values are stored after the lines in the files file1.txt,file.txt are splited according to space " " .
how is %o association being formed in this case i believe that is what you are refering by saying the $o{$h} . After the condition is true you are trying to substract $n[0]..that would be 10 or 15 and you are refering the $o{$h} is the same value if the association is being formed from spilt.
Thanks for your help in advance
2 REPLIES 2
Hein van den Heuvel
Honored Contributor
Solution

Re: help me understand this perl one liner

Hello again Abdul,

And I actually had a bit of comment/explanation with the original topic.

Anyway, let me re-arrange the code and add comment some more:

1) perl -ne '' file1.txt file2.txt

Execute 'prog' perl in an implied loop reading through all input files, setting variable $_ to the next line in the input for each iteration.

2) ($h,$n)=split;

As you indicate, split data from default variable $_ using default 'whitespace' seperators. Here $h = host, $n = number.

3) if ($old=$o{$h})

%o is an associative array.
$o{$h} is an element from %o with key value $h (here host)
So this TRIES to pick an already stored number for host.
If that worked THEN

4) {print "$h : ", $n - $old, "\n"}

Print the host name and the difference between the current number and the old, already remembered number.

5) else {$o{$h}=$n}

ELSE... if there was no old number saved for host $h, then save it now: Create and element with key $h and value $n in array %o

Sort of.. but through variables... do:
%o{"host1-80"} = 20;

More clear?

Anyone else see anythign that needs explanation here?

Cheers,
Hein.



Abdul khadeer_1
Occasional Advisor

Re: help me understand this perl one liner

Thanks Hein, for your time .i hope i will be able to write the program as you showed in this case