Array and Hashes: I am confused!

06/03/2013 - 21:55 von Ying Gan | Report spam
I do not understand what this means:
if ($#raw == 1) {
$names{$raw[1]} = $raw[0];

Here is the perl-script from which I have taken (if ($#raw == 1) {
$names{$raw[1]} = $raw[0];)

$in = ''; #
%names = (); # Hash: names
@raw = (); # words
$fn = ''; # firstname
while () {
print 'Enter a name (firstname and middlename): ';
chomp($in = <STDIN>);
if ($in ne '') {
@raw = split(' ', $in);
if ($#raw == 1) {
$names{$raw[1]} = $raw[0];
} else {
$fn = '';
$i = 0;
while($i < $#raw) {
$fn .= $raw[$i++] . ' ';
}
$names{$raw[$#raw]} = $fn;
}
}
else { last; }
}
foreach $lastname (sort keys %names) {
print "$lastname, $names{$lastname}";
}


Thank you very much for your help!!!!!
 

Lesen sie die antworten

#1 K. Wittrock
07/03/2013 - 10:59 | Warnen spam
Ying Gan schrieb am 06.03.2013 :
I do not understand what this means:
if ($#raw == 1) {
$names{$raw[1]} = $raw[0];



@raw is an array. $#raw is the highest index in use of the array.
if ($#raw == 1) {


checks whether @raw has exactly 2 elements.
$names{$raw[1]} = $raw[0];


If so, the value of the 1st element is copied to the hash %names,
taking the key from the 2nd element of @raw.

HTH.

Klaus

Meine Email-Adr. lautet
K<ohne_Punkt_und_Komma>Wittrock<Klammeraffe>web.de

Ähnliche fragen