Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I have a tab delimited file, that looks like
a stuff morestuff
a otherstuff morestuff
a yetmorestuff things
b stuff morestuff
b things2 3things

I read the file into an array @hitlist. Individual lines are parsed as arrays @array. I want to take the element @array[0] and make an array by that name. How do I go about doing that? I know that I can call up @array[0] by $array[0] but I can't make a new array called @\$array[0] or @$array[0].
What did I miss?
thanks

Replies are listed 'Best First'.
Re: Array named for array element?
by Abigail-II (Bishop) on Jul 02, 2003 at 19:52 UTC
    You can do that with symbolic references:
    no strict 'refs'; @{"$array[0]"} = (1, 2, 3, 4);

    Having said that, why would you want to do that? In most programming languages, you can't do that, and people don't even ask how to do that. In Perl, it's not at all necessary, it's potentially dangerous, and considered bad programming style. Now that I've told you how to do it, answer my question: Why would you want to do this?

    Abigail

      The reason I want to do it this way is because the script I'm writing is to be used for files of varied length with differing frequencies of the first element occurring in the text. And the first element will vary between different files. I'm thinking this might be best done with an array of arrays, where the array is named for the first element, and the arrays underneath would have the rest of the data.

        Then you definitely want a hash of arrays just like everyone else suggested. :)

        --
        Allolex

Re: Array named for array element?
by Tomte (Priest) on Jul 02, 2003 at 19:52 UTC

    Rethink the design
    If you end up with dynamicaly named complex storages, you normaly really want to use a hash ;)

    In your case something like

    my %hash = ( a => [ ['stuff', 'morestuff'], ['otherstuff', 'morestuff'], ['yetmorestuff','things'] ], b => [ ['stuff','morestuff'], ['things2','3things'], ], );
    seems to be reasonable, but who knows but you, you didn't say what you want to do with all that stuff...

    regards,
    tomte


    Hlade's Law:

    If you have a difficult task, give it to a lazy person --
    they will find an easier way to do it.

Re: Array named for array element?
by tcf22 (Priest) on Jul 02, 2003 at 19:51 UTC
    First off, I wouldn't recommend generating variable names on the fly. Perhaps you could use a hash who's values are array refs.

    For example:
    my %hash; foreach(@hitlist){ ..DO PARSING - BUILDING @array.. my $name = shift @array; %hash{$name} = \@array; }
Re: Array named for array element?
by BUU (Prior) on Jul 02, 2003 at 19:53 UTC