2011年10月13日 星期四

chomp reading to get @arr,%hash



@colors = ();
while($line = <STDIN>)
{
  $nr+=chomp $line;
  push(@colors, $line);
}
print "\@colors = @colors\n";
print "Newlines removed: $nr";


The output will be identical as in the previous example shown above.
Next, let’s see an example when the Perl chomp function is called with a hash as argument. This will be illustrated in the following code segment. But before seeing the example, I want to specify that, like as in the case of the chop()function, only the values of a hash are chomped, the keys being left unchanged. After processing all the elements of a hash, the Perl chomp function will return the number of chomped characters.



# read the pair elements of the hash from STDIN 
chomp(%fruitsColors = <STDIN>);
# the next loop prints the keys/values of the hash
foreach $key (keys %fruitsColors)
{
  print "Key: $key, Value: $fruitsColors{$key}\n";
}


For this code, here is an output example:



C:\Perl\bin>perl chomptst.pl
apricot
yellow
cherry
red
plum
dark blue
^Z in Windows (^d in Linux)
Key: plum
, Value: dark blue
Key: apricot
, Value: yellow
Key: cherry
, Value: red



chomp可移除hash 中的value的\n符號 ,
但chomp不移除key的\n符號

# create a new hash – fruitsColors 
# and assigning some elements to it
$fruitsColors{"plum\n"}="dark blue\n";
$fruitsColors{"apricot\n"}="yellow\n";
$fruitsColors{"cherry\n"}="red\n";
# chomp the hash
$nr = chomp(%fruitsColors);
# the next loop prints the keys/values of the hash
foreach $key (keys %fruitsColors)
{
  print "Key: $key, Value: $fruitsColors{$key}\n";
}
print "newlines removed: $nr\n";

The output for this short script:

C:\Perl\bin>chomptst.pl
Key: apricot
, Value: yellow
Key: plum
, Value: dark blue
Key: cherry
, Value: red
newlines removed: 3

As you see in this example, the number of newlines removed was 3 meanwhile the Perl hash keys remained "unchomped".

沒有留言:

張貼留言