I am having difficulty getting my head around this considering variable declarations. Scenario: I have a file with ten words, one per line. First I want to loop through the file and create new files based on the data. Example
banana
apple
coconut
strawberry
-->
banana.txt
apple.txt
coconut.txt
strawberry.txt
The first problem that I'm having is: how do I assign a unique variable for the file handle for each file in the loop? I would write something like this but I don't know if that's the way to go:
open(my $tokensfh, '<', $tokensfile)
or die "cannot open file $tokensfile";
chomp(my @tokenslines = <$tokensfh>);
close $tokensfh;
foreach my $token(@tokenslines) {
open(my $token.'fh', '>>', $token."data.txt");
}
A bit further down the line I match other data against the $token, but I'm unsure how to deal with the variables:
foreach my $somedata(@data) {
my $datatoken = $somedata=~ /<fruit>(.+)<\/fruit>/;
# Do I need a new variable name here?
foreach my $tokensline(@tokenslines) {
if ($datalinetoken eq $datatoken ) {
# print $somedata to specific file
print $tokensline.'fh' "average run time\n";
}
}
}
Do I need a new variable name? If not, how can I re-use the earlier variable without getting variable assignment issues? Is there a better way to do this? (Please answer all questions.)