寒假【perl语言学习脚本】6.1 6.2 6.3

寒假【perl语言学习脚本】6.1 6.2 6.3
#!/usr/bin/perl -w
my %gf_name = (
dongzhu => ‘yang’,#=>胖箭头
lin => ‘zhou’,
fangfang => ‘zhang’,
);
print “please input the name:\n”;
chomp(my $person= );
if (exists KaTeX parse error: Expected '}', got 'EOF' at end of input: gf_name{person}){
print “hey,$person exists there\n”;
}
#用exists函数检查哈希的键是否存在
print “her name is KaTeX parse error: Expected '}', got 'EOF' at end of input: gf_name{person} KaTeX parse error: Expected 'EOF', got '\n' at position 9: person .\̲n̲"; #哈希就是一个键值对的形…word);#声明变量
chomp(@words=);
foreach $word(@words){
KaTeX parse error: Expected '}', got 'EOF' at end of input: count{word}+=1;#KaTeX parse error: Expected '}', got 'EOF' at end of input: count{word}=KaTeX parse error: Expected '}', got 'EOF' at end of input: count{word}+1
}
foreach $word (sort keys %count){ #my count=keysprint"count =keys %hash;得到3,也就是说有三对键值 p125 sort根据ASCII编码排序 print "word was seen KaTeX parse error: Expected '}', got 'EOF' at end of input: count{word} times.\n”;
}
#foreach循环会逐项处理各个单词,它会将KaTeX parse error: Expected '}', got 'EOF' at end of input: count{word}的值加上1,然后再存回KaTeX parse error: Expected '}', got 'EOF' at end of input: count{word}
#在第一份foreach循环里,每次出现的单词都会让KaTeX parse error: Expected '}', got 'EOF' at end of input: count{word}的值加1
#假设第一个单词是fred,那么count"fred"1count{"fred"}的值就会加1,既然是第一次用到count{“fred”},它的值自然是undef
#不过,因为我们将它当成数字来用(利用数字操作符+=或是较长写法的+)
#所以perl会自动把undef转换为0,相加的总和为1,所以会将1存回$count{“fred”}

寒假【perl语言学习脚本】6.1 6.2 6.3
#!/usr/bin/perl -w
my $longest =0;
foreach my $key(keys %ENV){ #帮助确定第一列的宽度
my keylength=length(key_length=length(key);
longest=longest=key_length if keylength>key_length>longest;
}#帮助确定第一列的宽度

foreach my key(sortkeysprintf"key(sort keys %ENV){#依次处理hash,对键值进行排序 printf "%-{longest}s %s\n",key,key,ENV{$key};#宽度字符是负的,是让字符串左对齐,一一对应
}