Anden120
Anden120

Reputation: 13

Perl - Inconsistent output

This is the code that is matching users and their home storage capacity, the strange thing is that it yields the same result five times, instead of five unique results as it's meant to.

open( my $storage_input, "du -shc /home/*|" );

while ( my $line3 = <$storage_input> ) {
    push( @user_storage, $line3 );
}

foreach my $line3 ( @user_storage ) {
    if ( $line3 =~ m/^([0-9](.){1,})M\s+\/[a-z]{1,4}\/([a-z]{4}|[a-z]{1}\d{2}[a-z]{5})/ ) {
        %storage = ( "data" => "$1", "user" => "$3", );
        push( @storage_data, \%storage );
    }

}

print "\n";

foreach ( my $i = 0 ; $i < scalar( @storage_data ) ; $i++ ) {
    print $storage_data[$i]{"user"};
    print " has used ";
    print $storage_data[$i]{"data"};
    print " MiB of storage.\n";
}

This is the command output that we are matching:

3.4M    /home/jony  
3.4M    /home/luha  
40M /home/maho  
35M /home/mipa  
3.0M    /home/svkn  

Upvotes: 0

Views: 99

Answers (1)

choroba
choroba

Reputation: 242323

You push a reference to %storage to @storage_data, and then change %storage. You should use a different %storage for each iteration of the loop, i.e. prepend my to its assignment.

my %storage = (

Do you use strict?

Alternatively, you can store an anonymous hash:

push @storage_data, { data => "$1",
                      user => "$3",
                    };

Upvotes: 2

Related Questions