in reply to Perl parse text file using hash
Looking at the original code, a few things stand out:
Rewriting your program to show the data you got:
#!/usr/bin/perl use 5.014002; use warnings; my @fruits; my %info = parse ("test.txt"); # %info now holds: # { Albert => { # apple => { # path => '/path/to/somewhere/a' # } # }, # Dex => { # jackfruit => { # path => '/path/to/somewhere/d' # } # }, # Jack => { # apple => { # path => '/path/to/somewhere/c' # }, # pineapple => { # path => '/path/to/somewhere/b' # } # } # } foreach my $name (sort keys %info) { foreach my $fruit (sort @fruits) { printf "%-7s %-12s %s\n", $name, $fruit, $info{$name}{$fruit}{path} // "-"; } } sub parse { my $file = shift; my %info; -e $file or return; open my $fh, "<", $file or die "Can't open $file: $!\n"; say "-I-: Reading from config file: $file"; my %seen; while (<$fh>) { m/^\s*(?:#|\s*$)/ and next; my @fields = split m/\s+/ => $_; my ($name, $fruit, $p) = @fields; $seen{$fruit}++ or push @fruits => $fruit; $info{$name}{$fruit}{path} = $p; } close $fh; return %info; } # parse
Will - with your test data - result in:
-I-: Reading from config file: test.txt Albert apple /path/to/somewhere/a Albert jackfruit - Albert pineapple - Dex apple - Dex jackfruit /path/to/somewhere/d Dex pineapple - Jack apple /path/to/somewhere/c Jack jackfruit - Jack pineapple /path/to/somewhere/b
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Perl parse text file using hash
by hv (Prior) on Dec 20, 2022 at 18:17 UTC |