Hash or hash's of hash?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • armbsu
    New Member
    • Jun 2012
    • 1

    Hash or hash's of hash?

    Hello,

    I am a beginner in Perl. I am trying to read and then process a pipe delimited file. My file looks something like this-

    size|3
    directory|c:\un icorn
    sub-directories|sub |new.....

    The examples I have seen online show code where it is known how many columns the file consists. However, this is going to be a configuration file and number of columns in sub-directories is unknown.

    My question is what do I need has or hash's of hash or something else in this case?

    Thanks!
  • RonB
    Recognized Expert Contributor
    • Jun 2009
    • 589

    #2
    You can use a hash, or a hash of arrays, or a hash of hashes. You haven't provided enough info for use to be able to make a clear recommendation.

    Is the file format set in stone i.e., is it being dictated by your instructor/boss? If you can, I'd recommend changing it to a more standard config file format and possibly use one of the config modules on cpan to parse it.

    Comment

    • RonB
      Recognized Expert Contributor
      • Jun 2009
      • 589

      #3
      Here's one option.

      Code:
      #!/usr/bin/env perl
      
      use strict;
      use warnings;
      use Data::Dumper;
      
      my %cfg;
      
      while (my $line = <DATA>) {
          chomp $line;
          my ($key, @values) = split /\|/, $line;
          
          if (@values > 1) {
              $cfg{$key} = \@values;
          }
          else {
              $cfg{$key} = $values[0];
          }
      }
      print Dumper \%cfg;
      
      __DATA__
      size|3
      directory|c:\unicorn
      sub-directories|sub|new
      which outputs:
      Code:
      $VAR1 = {
                'sub-directories' => [
                                       'sub',
                                       'new'
                                     ],
                'directory' => 'c:\\unicorn',
                'size' => '3'
              };

      Comment

      • numberwhun
        Recognized Expert Moderator Specialist
        • May 2007
        • 3467

        #4
        If I may add to this, take a look at this link. I have used it as a reference for hashes in Perl and it has been extremely handy. Hopefully it helps.

        Regards,

        Jeff

        Comment

        Working...