On Jan 27, Rob Dixon said:

>Sam wrote:
>>
>> sub print_lines_ok {
>>     my ($output, $blank_lines) = @_;
>>     if ($blank_lines) {
>>         do {
>>             print if $output;
>>             $_ = <>;
>>         } while (/^\s*$/ and not eof);
>>     } else {
>>         do {
>>             print if $output;
>>             $_ = <>;
>>         } while (not /^\s*$/ and not eof);
>>     }
>> }
>>
>>
>> sub print_lines_ideal {
>>     my ($output, $blank_lines) = @_;
>>     my $expr = $blank_lines ? '/^\s*$/' : 'not /^\s*$/';
>>
>>     do {
>>         print if $output;
>>         $_ = <>;
>>     } while (eval $expr and not eof);  # works, but not fast.
>>                                        # Can I move eval out of loop?
>> }

You could just say

  do ... while (($blank ? /^\s*$/ : not /^\s*$/) and not eof);

which could be written with 'xor' as Rob shows below:

  do ... while ($blank xor not /^\s*$/) and not eof;

and 'not /^\s*$/' can be written as /\S/, which results in Rob's code.

>I don't think you want what you've written, as the first call to 'print'
>is before anything has been read from the file. This should come close:
>
>  sub print_lines {
>    my ($output, $blank_lines) = @_;
>    while (<>) {
>      last if $blank_lines xor /\S/;
>      print if $output;
>    }
>  }

That might work in this specific case, but if you want to be able to
change the course of events like that without constant re-evaluation, I'd
suggest using code references:

  my $code = \&first;

  sub first {
    # code for the first case
    if (some condition) { $code = \&second }
  }

  sub second {
    # code for the second case
  }

  $code->();

-- 
Jeff "japhy" Pinyan      [EMAIL PROTECTED]      http://www.pobox.com/~japhy/
RPI Acacia brother #734   http://www.perlmonks.org/   http://www.cpan.org/
<stu> what does y/// stand for?  <tenderpuss> why, yansliterate of course.
[  I'm looking for programming work.  If you like my work, let me know.  ]


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to