in reply to How do you read the next line in a file while in a loop?

Perhaps something like this is what you want......
#!/usr/bin/perl -w use strict; my (%options,$curroption); while(<DATA>) { # read from __DATA__ filehandle below chomp; # get rid of trailing newlines next if /^\s*#/; # skip if it the first nonspace char is '#'. # set the curroption if the first item in the line is in all caps $curroption = $1 if s/^([A-Z]+) //; # make $currroption a hash key whose value is an array ref containin +g # the various options we found. push(@{$options{$curroption}},$_) for (split(/,\s*/)); } # print the datastructure which is a HoA (Hash of Arrays); for my $option (keys %options) { my @vals = @{$options{$option}}; print "$option -- ", join (',',@vals), "\n"; } __DATA__ # comment # comment ON Mon, Tues, Fri, Sat # comment other stuff
Output:
ON -- Mon,Tues,Fri,Sat,other stuff

-Blake

Replies are listed 'Best First'.
Re: Re: How do you read the next line in a file while in a loop?
by Hofmator (Curate) on Aug 31, 2001 at 12:56 UTC

    Nice answer, ++blakem! Let me make some small remarks - your code has slight differences to the specifications ...

    • next if /^\s*[#*]/; # comments start with # or *
    • $curroption = $1 if s/^([A-Z]+) //;GroundZero is matching the option case insensitive - but this would break your code and you would have to resort to the comma-at-end-of-line solution suggested by grinder. As I understood the problem, the options (like on, except, ...) are known beforehand. In that case your elegant solution is easily fixable:
      # at top of program my @options = qw/on except some more options/; my $opt_string = join '|', @options; my $opt_pattern = qr/^($opt_string)\s+/i; # instead of your line $curroption = $1 if s/$opt_pattern//;
      and everything should be fine - as long as the option keywords are not allowed as values for any of the options.
    • push accepts a list: push @{$options{$curroption}}, split(/,\s*/);
    • Instead of the for loop I'd use a while (each) construct:
      while (my ($option, $val_ref) = each %options) { print "$option -- ", join (',',@$val_ref), "\n"; }

    -- Hofmator

Re: Re: How do you read the next line in a file while in a loop?
by GroundZero (Initiate) on Aug 31, 2001 at 03:00 UTC
    Thanks Blake, I like your code it looks really close to what I want, but I don't want ', other stuff' it would be another section of data. It would be like..
    ON Mon, Tues, Fri EXCEPT Sun, Mon And I would want ouput like on = Mon,Tues,Fri execpt = Sun,Mon
    Maybe I am not explaining myself well.
      Have you tried replacing the data after __DATA__ with the data you have provided here? I think it already works that way....

      -Blake