in reply to Re^2: Group __DATA__ lines in a while?
in thread Group __DATA__ lines in a while?
How about delayed execution? You push all commands onto a stack and only execute after reading all data:
sub story { my ($source,$author) = @_; my $tab = 3; my @toc; my @commands; push @commands, [ \&startsection, "Lead" ]; # I ran $source above, so I can't have it here! /me head desks. while (my $line = <$source>) { chomp($line); # If a line starts with a bracket, just print the line. if ($line =~ m/^</) { push @commands, [ \&line, $tab, $line ]; } # If a line starts with a numeral 1-6, print a heading. elsif ($line =~ /^[1-6]\s/) { my ($heading,$text) = split(/ /,$line,2); if( $heading == 2 ) { push @toc, anchor($text, { href => '#'.idify($text) } +); if( $commands[-1]->[0] eq \&startsection ) { # not sur +e this comparison is valid... pop @commands; # to avoid empty sections } else { push @commands, [ \&endsection ]; } push @commands, [ \&startsection, $text ]; # adapt arg +uments as required } my $id = idify($text); push @commands, [ \&heading, $tab,$heading,$text, { id => +$id } ]; } # If a line is a break or horizontal rule, print the line in b +rackets. elsif ($line =~ /^[bh]r$/) { push @commands, [ \&line, $tab, "<$line>" ]; } # All other lines are paragraphs. else { push @commands, [ \¶graph, $tab, $line ]; } } push @commands, [ \&endsection ]; # do the table of contents list($tab, 'u', \@toc, { class => 'two' }); # delayed execution of all print commands for (@commands) { my $cmd = shift @$_; $cmd->(@$_); } # If I wrote a story, I want people to know I wrote it at the bott +om. paragraph($tab,"written by $root_user", { class => 'author' }) if +!$author; }
I cannot test this code but it hopefully conveys the idea...
startsection and endsection would be two subs to print the HTML to start and end a section.
Update: some changes in formatting of the post and added a missing comma in the code.
Update: added a missing endsection at the end.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: Group __DATA__ lines in a while?
by Lady_Aleena (Priest) on Oct 21, 2013 at 07:51 UTC | |
by hdb (Monsignor) on Oct 23, 2013 at 09:32 UTC | |
by Lady_Aleena (Priest) on Nov 10, 2013 at 23:16 UTC | |
by hdb (Monsignor) on Nov 11, 2013 at 08:44 UTC | |
by Lady_Aleena (Priest) on Nov 11, 2013 at 10:14 UTC | |
| |
by Lady_Aleena (Priest) on Oct 24, 2013 at 04:48 UTC |