开发者

Can't make sense out of this Perl code

This snippet basically reads a file line by line, which looks something like:

Album=In Between Dreams
Interpret=Jack Johnson
Titel=Better Together
Titel=Never Know
Titel=Banana Pancakes
Album=Pictures
Interpret=Katie Melua
T开发者_如何转开发itel=Mary Pickford
Titel=It's All in My Head
Titel=If the Lights Go Out
Album=All the Lost Souls
Interpret=James Blunt
Titel=1973
Titel=One of the Brightest Stars

So it somehow connects the "Interpreter" with an album and this album with a list of titles. But what I don't quite get is how:

while ($line = <IN>) {
    chomp $line;
    if ($line =~ /=/) {
        ($name, $wert) = split(/=/, $line);
    }
    else {
        next;
    }
    if ($name eq "Album") {
        $album = $wert;
    }
    if ($name eq "Interpret") {
        $interpret = $wert;
        $cd{$interpret}{album} = $album; // assigns an album to an interpreter?
        $titelnummer = 0;
    }
    if ($name eq "Titel") {
        $cd{$interpret}{titel}[$titelnummer++] = $wert; // assigns titles to an interpreter - WTF? how can this work?
    }
}


The while loop keeps running and putting the current line into $line as long as there are new lines in the file handle <IN>. chomp removes the newline at the end of every row.

split splits the line into two parts on the equal sign (/=/ is a regular expression) and puts the first part in $name and the second part in $wert.

%cd is a hash that contains references to other hashes. The first "level" is the name of interpreter.

(Please ask more specific questions if you still do not understand.)


cd is a hash of hashes. $cd{$interpret}{album} contains album for interpreter.

$cd{$interpret}{titel} contains an array of Titel, which is filled incrementally in the last if.

Perl is a very concise language.


The best way to figure out what's going on is to inspect the data structure. After the while loop, temporarily insert this code:

use Data::Dumper;
print '%cd ', Dumper \%cd;
exit;

This may have a large output if the input is large.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜