Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re: Perl parse text file using hash

by BillKSmith (Monsignor)
on Dec 20, 2022 at 14:40 UTC ( [id://11148993] : note . print w/replies, xml ) Need Help??


in reply to Perl parse text file using hash

I recommend that you combine name and fruit into one key. I assume that the character '!' will never appear in the name of any person or fruit.
use strict; use warnings; use autodie; my $file = \<<'EOF'; Albert apple /path/to/somewhere/a Jack pineapple /path/to/somewhere/b Jack apple /path/to/somewhere/c Dex jackfruit /path/to/somewhere/d EOF open( my $fh, '<', $file); my %info; while (<$fh>) { my @fields = split; my $key = "$fields[0]!$fields[1]"; my $path = $fields[2]; $info{$key} = $path; } close $fh; my $name = 'Jack'; my $fruit = 'pineapple'; my $path = $info{"$name!$fruit"};
Bill

Replies are listed 'Best First'.
Re^2: Perl parse text file using hash
by LanX (Saint) on Dec 20, 2022 at 16:34 UTC
    Hi Bill

    > I assume that the character ! will never appear in the name of any person or fruit.

    Actually you are reinventing the wheel here.

    Perl has a built-in mechanism for multidimensional keys.

    • $foo{$x,$y,$z}
    • ... is equivalent to ...
    • $foo{join($;, $x, $y, $z)}

    see $; aka $SUBSCRIPT_SEPARATOR in perlvar

    Cheers Rolf
    (addicted to the 𐍀𐌴𐍂𐌻 Programming Language :)
    Wikisyntax for the Monastery

      Rolf, That is a cleaver use of the Multi-Dimensional Array Emulation syntax even though that is not exactly what we are doing.

      In the spirit of 'not inventing a wheel', perl can also do the input, looping and splitting for us if we use the -n and -a command switches. (perlrun).

      #!perl -na use strict; use warnings; our %info; $info{$F[0],$F[1]} = $F[2]; END{ my $name = 'Jack'; my $fruit = 'pineapple'; my $path = $info{$name,$fruit}; print "$name $fruit $path\n"; }

      OUTPUT:

      >perl 1114899a.pl paths.csv Jack pineapple /path/to/somewhere/b
      Bill