[英]Perl Hash + While add elements
I need store each element in the first column where are the privileges in keys and value in the file, i did this but I do not understand. 我需要将每个元素存储在第一列中,该位置是文件中键和值的特权,我这样做是不知道的。
it's content in my file "file-privilege" 它在我的文件“ file-privilege”中的内容
-rw-rw-r--. file-privilege
-rw-rw-r--. file-selinux
-rwxrwxrwx. funcion-split-join.pl
-rwxrwxr-x. hash2.pl
-rw-rw-r--. hash3.pl
-rwxrwxr-x. hash.pl
-rwxrwxr-x. inthashfile.pl
-rw-rw-r--. ls
-rwx------. probando.pl
the code in perl. Perl中的代码。
%pr_file = ();
open(WHO, "file-privilege");
while (<WHO>) {
($privilege, $file) = split ;
push( @{$pr_file{$privilege}}, $file );
}
this output. 此输出。
-rwx------. = ARRAY(0x83bb7f0)
-rw-rw-r--. = ARRAY(0x83a06f8)
-rwxrwxr-x. = ARRAY(0x83bb780)
-rwxrwxrwx. = ARRAY(0x83bb750)
I need: 我需要:
key = value 键=值
-rw-rw-r--. = file-privilege
etc... 等等...
any idea? 任何想法?
The same key maps to multiple values. 相同的键映射到多个值。 You need to dereference the array reference just like when you add a value;
您需要像添加值一样取消引用数组引用。 or use a scalar which only remembers the last (or first, or a random) value.
或者使用仅记住最后一个(或第一个或随机值)的标量。
Anyway, the code you have shown us is correct; 无论如何,您显示给我们的代码是正确的; the problem is in the code which prints out the values, which you have not provided.
问题出在打印出您未提供的值的代码中。 But something like this:
但是这样的事情:
for my $priv (keys %pr_file) {
for my $file (@{$pr_file{$priv}}) {
print "$priv => $file"; # Already contains trailing newline
}
}
By the by, you should probably use Perl's built-in stat()
function rather than try to parse ls
output. stat()
,您可能应该使用Perl的内置stat()
函数,而不是尝试解析ls
输出。
Without seeing the code, you are probably doing: 没有看到代码,您可能正在做:
print "$privilege = $pr_file{$privilege}\n";
Since you are storing a list of filenames in an array reference $pr_file{$privilege}
, this code uses default stringification of an array reference , by printing "ARRAY(address)". 由于您将文件名列表存储在数组引用
$pr_file{$privilege}
,因此该代码通过打印“ ARRAY(address)”来使用数组引用的默认字符串化。
When you are printing the results, you need to stringify you arrayref of file names in a more useful format yourself: 打印结果时,您需要自己以更有用的格式对文件名的arrayref进行字符串化:
print "$privilege = $pr_file{$privilege}->[0]\n"; # Print the first file in the list
print "$privilege = $pr_file{$privilege}->[-1]\n"; # Print the last file in the list
my $files_string = join(",", @{ $pr_file{$privilege} })); #Comma separated files
print "$privilege = $files_string\n"; # Print all files, comma separated
my @files = @{ $pr_file{$privilege} }); # Dereference the array ref into array
print "$privilege = @files\n"; # Print all files, space separated.
# Uses default stringification of an array
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.