Unquoted string "fred" may clash with future reserved word at ./perl.pl line 762.
String found where operator expected at ./perl.pl line 762, near "fred" }""
syntax error at ./perl.pl line 762, at EOF
Execution of ./perl.pl aborted due to compilation errors.
这是为什么啊?
那是因为你的“”里面还有“”,而perl会把第二个“和前面的”匹配,导致出错,你可以这样
print "$count{ \"fred\" }"
这个涉及到perl包了吧只能写代码给你看了,细节可能需要自己去查资料。
1、建立一个文件,用于存储你的哈希表,名为MyHashTb.pm,里面的代码为:
#!usr/bin/perl -w
use strict
package MyHashTb
sub new
{
my $class = shift @_
my $ref = {}
bless $ref,$class
return
}
sub set
{
my $class = shift @_
$class ->{"key1"} = "value1"
$class ->{"key2"} = "value2"
...
$class ->{"keyN"} = "valueN"
}
sub get
{
my ($class,$key) = @_
return $class ->{$key}
}
1
#以package开头必须以1结尾
2、将MyHashTb.pm这个文件放到perl存放模块的目录下,之后其他.pl的perl程序可以通过以下代码调用它:
#!usr/bin/perl -w
use strict
use MyHashTb
my $key1 = "key1"
my $key2 = "key2"
my $hash_tb = MyHashTb ->new()
$hash_tb ->set()
my $value1 = $hash_tb ->get($key1)
my $value2 = $hash_tb ->get($key2)
1、如果是按ASCII码(字符串)排序,则代码如下:foreach my $key ( sort { $hash{$a} cmp $hash{$b} } keys %hash ) {
my $value = $hash{$key}
# do something with ($key, $value)
}
2、如果是按数字大小排列,则代码如下:
foreach my $key ( sort { $hash{$a} <=>$hash{$b} } keys %hash ) {
my $value = $hash{$key}
# do something with ($key, $value)
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)