DARK SCIENTIST has asked for the wisdom of the Perl Monks concerning the following question:

Hello fellow Perl users... having some trouble here. Say for example, I have a text file containing two short stories. Above each short story there is a title formatted like: "<Baking Cookies>". I want to use each story title as a hash key, and the remaining text (story) as the value so when it reaches the next story title it will assign a new key. I have some code for this but it's not working properly. Suggestions are much appreciated... Please excuse my lack of experience. Thanks!

open FILE, "$dir/$file" or die ("Invalid file!\n"); my @stories = <FILE>; my $title = ''; my %stories_hash = (); foreach my $line (my @stories){ if($line =~ /<(.*)>/){ $title = $1; } else { $stories_hash{$title} .= $line; } }

Replies are listed 'Best First'.
Re: Parsing a text file
by huck (Prior) on Apr 15, 2017 at 17:38 UTC

    In this line foreach my $line (my @stories){ the my makes a new copy of the array stories that is in effect for the lexical block of the foreach. Of course that new copy is empty rather than having the contents of the file in it. Use foreach my $line (@stories){ instead;

      What a mistake for me to make!! I read so much to learn how to take different approaches and I still make silly mistakes like that. Thanks a bunch for your reply huck