I have a database made up of .dat files that are formatted as follows:

UserID001|username1|password1|displayname1| UserID002|username2|password2|displayname2| UserID003|username3|password3|displayname3| ...

This is only one record of the database, and many other records will be formatted in this same fashion but with varying numbers of columns. I am trying to write a subroutine to accept each record as an array, then return a hash for each column using the UserIDs as the hash keys.

I'm assuming it will be best to return references to these hashes, but I'm not sure how to dynamicly create a hash for each column. Here's what I have so far:

# Calling the subroutine ($usernamesRef,$passwordsRef,$displaynamesRef) = arrayToMultiHash (\@u +sers); %usernames = %{$usernamesRef}; %passwords = %{$passwordsRef}; %displaynames = %{$displaynamesRef}; # The subroutine sub arrayToMultiHash { my @array = @{$_[0]}; my @hashRefs; foreach $line (@array) { my @lineInfo = split (/\|/,$line); my $key = shift (@lineInfo); my $i = 0; foreach $value (@lineInfo) { my $hashName = "hash$i"; $hashName{$key} = $value; $i++; } } foreach (0..$i) { my $hashName = "hash$i"; push (@hashRefs,\%{$hashName}); } return (@hashRefs); }

Any help will be greatly appreciated. Thank you in advance.


In reply to Creating dynamic hash names by Lamont85

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.