in reply to How to read lines from a file which is....
#!/usr/bin/perl -w use strict; die "Usage: save-into-arrays.pl input-file.txt\n" unless @ARGV == 1; my @description; # where we'll store contents of Description sectio +n my @data; # where we'll store contents of Data section my %sections = ('Description:' => \@description, 'Data:' => \@data); open(INPUT_FILE, "<$ARGV[0]") or die "Unable to open $ARGV[0]: $!\n"; my $array_ref; # keeps reference to array currently in use while (my $line = <INPUT_FILE>) { chomp $line; if (defined($sections{$line})) { # is this is a section hea +d? $array_ref = $sections{$line}; # yes, so point to the arr +ay for this section } else { push @$array_ref, $line if $array_ref; # no, save this line in th +e active array } } close(INPUT_FILE);
Basically what this does is create a hash that pairs each possible section head with an array where you'll store the data from that section. When a section head is encountered, $array_ref gets updated to point to the right array for subsequent lines. This way when you have new section tags, you can just create a new array and a new entry for it in the hash -- no need to alter the underlying logic with more if statements, etc.
Cheers...
|
|---|