--- Bryan Gmyrek <[EMAIL PROTECTED]> wrote:
> I've written a program where I need to use an array of hashes.  The
> basic code I am having problems with is:
> 
> sub read_from_file{
> #input: file name that holds lines of info in the form  key: value
> #action: add these to an array of hashes
> #return: array of hashes
>       my $file = $_[0];
>       my @inputs;
>       my $i=0;
>       open(IN,"$file");
>       while(<IN>){
>               chomp;
>               if(/seperator/){
>                       $i++;
>               }
>               elsif(/category\:\s/){
>                       $inputs[$i]{category}=$';
>               }
>               elsif(/artist\:\s/){

Did you mean to say "artist" here, or "product"?

>                       $inputs[$i]{product}=$';
>               }
>       }
>       close(IN);
>       return @inputs;
> }
> 
> The input file is of the form:
> 
> seperator
> 
> category: example category
> 
> product: example artist
> 
> seperator
> 
> category: example category 2
> 
> product: example artist 2
> 
> and so on
> 
> So, in the end I think you should end up with an array of hashes in
> the form:
> 
> @inputs = (
>     {
>        category     => "example category",
>        product   => "example product",
>     },
>     {
>        category    => "example category 2",
>        product    => "example product 2",
>     },
> );

Looks right....

> My question is:
> 
> Why does it only 'sort of' work?  I call the routine later with:
> 
> my @other_array = &read_from_file("my_file");
> 
> and then I try to iterate over the new array of hashes and perform
> some functions, but only $other_array[1] holds any information
> ($other_array[0] should not, but $other_array[2] should)  

Might be the "artist"/"product" thing above....

> I'm totally stumped here, any suggestions?  Is it how I am returning
> the array?  Should I return a reference to the array or something
like
> that?

Might be clearer, but what you have is probably visually cleaner.
The array you're passing back is just a list of scalar references to
the hash elements of the my() array you made in the function anyway, so
it would seem more consistent. Just remember to receive it accordingly;
the way you're doing it, the array you have (which doesn't require any
special dereferencing) catches the elements of the sub's version, and
everything below that level is actually the same literal memory space.
Passing the array back as a non-ref just passes back a list of element
refs which you catch as element refs so they need no special handling.

__________________________________________________
Do You Yahoo!?
Get personalized email addresses from Yahoo! Mail - only $35 
a year!  http://personal.mail.yahoo.com/

Reply via email to