in reply to Re^4: Tutoring for beginner?
in thread Tutoring for beginner?
Yes, the code for reading the file is fine. People often use lexical filehandles these days, e.g.
open my $filea, "<", "Population.txt" or die "Cannot open: $!\n"; my @Data = <$filea>;
The reason for this is that "regular" filehandles are global -- in a short script it doesn't make a difference, but I believe it's best to get used to good style right away. (Also, short, throwaway scripts have a tendency to become longer and longer-lasting when you least expect it.)
So the list should be working with the text in the file? I'm trying to split each line in the list into two components.
For that you'll want to iterate over the lines, i.e. your @Data array, and split each individual line according to some rule. For iterating, you can use e.g. for or foreach (they're synonyms), like so:
# ... foreach my $line (@Data) { # do something with $line }
Depending on how large your input file is and how much of it needs to be kept in memory at the same time for processing, you may be better of not reading the entire file at once, and instead using a while loop to read it line by line:
open my $filea, "<", "Population.txt" or die "Cannot open: $!\n"; while(<$filea>) { # do something with $_ }
$_, BTW, is a special variable that acts as the default argument for many built-in functions; it's called the topic, and it's indeed pretty much that, the thing that is currently being talked about (i.e. processed). The angle bracket operator, when used in a while loop, assigns to $_ as well, so the above is a common idiom for processing a file line by line.
How you'd go about splitting a line into two components depends on where and how you want to split it. split is a useful function if you want to split on e.g. whitespace. If you can share some sample data and post a description of how you want it processed, we can help you further.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^6: Tutoring for beginner?
by Halbird (Novice) on Mar 07, 2015 at 14:19 UTC | |
by AppleFritter (Vicar) on Mar 07, 2015 at 17:25 UTC |