this_is_part_of_the_data__
so_is_this, #not a quote,
me_too.__And_there_are_lots_of_endings
musn't_forget_me!
on Mon______,______Tues__,___
Weds,
#comment
*different comment
Fri
#comment
turns into:
this_is_part_of_the_data__
so_is_this, #not a quote,me_too.__And_there_are_lots_of_endings
musn't_forget_me!
on Mon______,______Tues__,___
Weds,
Fri
until you have what can only be the end of a line, in this case one that does not match ,\s*$ Then you see if the beginning matches, then you split out the spaces and comma and use the results as you need.
It was a bit ambiguous if you had lots of sequences like this, each with a different key or not. So I assumed you did.
I take it you come from a c++ background?
:-)
Yves
#!/usr/bin/perl -w use strict; use warnings; my $text=<<'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; INPUT FILE = # comment # comment ON Mon, Tues, Fri, Sat # comment other stuff EXPECTED OUTPUT = $on = Mon,Tues,Fri,Sat XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX my %hash=(on=>undef, people=>undef); my $line=""; #open IN,$0; # uncomment me and replace the filehandle with SCAN:while(<DATA>) { # IN and it still works! next if /^\s*[*#]/; # line comments begin with * or # chomp; $line.=$_; # continue the line next if /,\s*$/; # not done my $found; KEY:foreach my $key (keys %hash) { if (!defined($hash{$key}) && $line=~/^\s*$key\s*/i) { $found=$key; last KEY; } } next SCAN unless $found; $line=~s/^\s*$found\s*//i; $hash{$found}=[split(/\s*,\s*/,$line)]; # split away $line=""; } # make printing easier $"=","; $,=$\="\n"; print "$text--OUTPUT--\n"; $"="','"; foreach my $key (keys %hash) { next unless $hash{$key}; print "#For Key '$key'"; print "my \@$key=qw('@{$hash{$key}}');\n"; } print "Hope this helps\n","Yves\n",":-)\n"; __DATA__ # comment # comment ON Mon, Tues, Fri, Sat # comment #INPUT FILE = ## comment ## comment People Mary, Bill, Jenny, Petra , Isolde, Joe #ON Mon, Tues, #Fri, #Sat ## comment #WISHFUL CODE = ##$infile = "test.txt"; ##$linecounter = 0; ##open(INFILE, $infile) || die "Can't open $infile : $!\n"; ##MAIN:while(<INFILE>) # ## $linecounter++; ## printf("File Line %s = %s",$linecounter, $_); ## if ( /^\*/ || /^\#/ ) # Get rid of useless comments in file. ## { ## next MAIN; ## } ## chop; ## if ( /^on/i ) ## { ## hold_on = ""; ## undef(@junk); ## @junk = split(' ', $_, 2); ## $hold_on = $junk[1]; ## $len = length($hold_on) - 1; ## $last_char = substr($hold_on, $len, 1); ## while ( $last_char eq "," ) ## { ## $read_line = readln(<INFILE>); ## $read_line =~ chop($read_line); ## $hold_on = "$hold_on$read_line"; ## $len = length($hold_on) - 1; ## $last_char = substr($hold_on, $len, 1); ## } ## $hold_on =~ s/\s//g; ## } ## #other code # ##printf("\$on = %s\n", $on);
In reply to Re: How do you read the next line in a file while in a loop?
by demerphq
in thread How do you read the next line in a file while in a loop?
by GroundZero
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |