1

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"

-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.

%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?

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

sub noc {foreach $user (sort keys %pr_file) { print "$user @{$pr_file{$user}}\n"; }} noc
2

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)".

When you are printing the results, you need to stringify you arrayref of file names in a more useful format yourself:

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

1 Comment

You can even do print "$privilege = @{ $pr_file{$privilege} }"; directly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.