John W. Krahn wrote:
>
> Sam wrote:
> >
> > # Print lines (or not) until a blank line is found (or not)
> > # This function works fine. But in the spirit of learning...read on.
> >
> > sub print_lines_ok {
> > my ($output, $blank_lines) = @_;
> > if ($blank_lines) {
> > do {
> > print if $output;
>
> You are printing the contents of $_ but you don't have anything in $_
> until the next line.
>
>
> > $_ = <>;
> > } while (/^\s*$/ and not eof);
> > } else {
> > do {
> > print if $output;
> > $_ = <>;
> > } while (not /^\s*$/ and not eof);
> > }
> > }
> >
> > # This function is the same thing; just more 'elegant' IMHO. :-)
> > # But it has its problems. I can eval it in the while loop and it
> > # works as it is below, but it's painfully slow. I *know* there's no
> > # need for the eval call every iteration but so far haven't figured
> > # out how to use eval outside the while AND have it work. It
> > # appears $expr is always true unless the eval is done in the while loop.
> > # In summary, how can I build a dynamic regexp that I can eval once
> > # and then use?
> >
> > sub print_lines_ideal {
> > my ($output, $blank_lines) = @_;
> > my $expr = $blank_lines ? '/^\s*$/' : 'not /^\s*$/';
> > # eval $expr # I want to eval this ONCE and then use it. Help?
> > do {
> > print if $output;
> > $_ = <>;
> > } while (eval $expr and not eof); # works, but not fast.
> > # Can I move eval out of loop?
> > }
>
> Perhaps this is what you want:
>
> sub print_lines_ideal {
> my ( $output, $blank_lines ) = @_;
> my $expr = $blank_lines ? qr/^\s*$/ : qr/\S/;
> while ( <> ) {
> print if $output and /$expr/;
> }
> }
Hi John.
It's hard to be sure, as we're guessing what the required algorithm is; but
the original code dropped out at the /first/ line that failed the blank or
non-blank test. Your solution may need to be:
while ( <> ) {
last unless /$expr/;
print if $output;
}
which I must say looks rather neat :)
Rob
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>