Depending on what you want to do with the data structure, you might want to build a hash of arrays as others have suggested. If you want to, say, validate makes and models, you might want a hash of hashes. To paraphrase some of what brian_d_foy posted above:
#!/usr/bin/perl use strict; use warnings; my %hash; my $make; while( <DATA> ) { chomp; if( /^(\S.*)/ ) { $make = $1 } elsif( /^\s+(\S.*)/ ) { $hash{$make}{$1} = 1 } elsif( /^\s*$/ ) { next; } } use Data::Dumper; print Dumper( \%hash ); # Valid - prints "Valid..." my ($make1, $model1) = qw(Nissan Maxima); print "Valid $make1 model1\n" if $hash{$make1}{$model1}; # Not valid - doesn't print my ($make2, $model2) = qw(Toyota Mustang); print "Valid $make2 model2\n" if $hash{$make2}{$model2}; # Valid - prints "Valid..." my $make3 = "Ford"; print "Valid $make3\n" if $hash{$make3}; __DATA__ Honda Civic Accord Toyota Camry Corolla Tundra Nissan Maxima
If dealing with makes by themselves is unnecessary, you can even use simulated multilevel hashes (saving some memory if there were a large number of makes and models) by changing this line:
elsif( /^\s+(\S.*)/ ) { $hash{$make}{$1} = 1 }
to this:
elsif( /^\s+(\S.*)/ ) { $hash{$make,$1} = 1 }
And then validate with this:
print "Valid $make1 $model1\n" if $hash{$make1,$model1};

In reply to Re: hashes with arrays by runrig
in thread hashes with arrays by magawake

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.