diff options
author | James E Keenan <jkeenan@cpan.org> | 2022-08-10 14:27:41 +0000 |
---|---|---|
committer | James E Keenan <jkeenan@cpan.org> | 2022-08-10 14:29:17 +0000 |
commit | 4d4eaa2cb3eb05793dc301178e47fe89488a88f0 (patch) | |
tree | dd8acf937639ad8ec0d3df715cb023c7b73ba332 /pod/perlfunc.pod | |
parent | 3fd12c9d6f086a9b0c50794a78d1c078fcb5498d (diff) | |
download | perl-4d4eaa2cb3eb05793dc301178e47fe89488a88f0.tar.gz |
Document C<local *STDOUT> as an alternative to C<select ... select>
If one needs to temporarily "capture" the output of C<print>, for example
as part of a unit test, the classic "obvious" approach has been to use
C<select> before and afterwards, to set a different default output handle
and the restore the previous handle.
If one is already in the mindset of C<select>, it might not be obvious
that C<local *STDOUT> is alternative way to achieve the underlying goal,
and might be clearer and more robust. Hence add it as a suggestion in the
C<select> documentation.
For: https://github.com/Perl/perl5/pull/19225; reconciling different
approaches developed by @nwc10 and @leonerd.
Diffstat (limited to 'pod/perlfunc.pod')
-rw-r--r-- | pod/perlfunc.pod | 28 |
1 files changed, 28 insertions, 0 deletions
diff --git a/pod/perlfunc.pod b/pod/perlfunc.pod index 13f81317bb..38ebb0d12d 100644 --- a/pod/perlfunc.pod +++ b/pod/perlfunc.pod @@ -7170,6 +7170,34 @@ methods, preferring to write the last example as: (Prior to Perl version 5.14, you have to C<use IO::Handle;> explicitly first.) +Whilst you can use C<select> to temporarily "capture" the output of +C<print> like this: + + { + my $old_handle = select $new_handle; + + # This goes to $new_handle: + print "ok 1\n"; + ... + + select $old_handle; + } + +you might find it easier to localize the typeglob instead: + + { + local *STDOUT = $new_handle; + + print "ok 1\n"; + ... + } + +The two are not exactly equivalent, but the latter might be clearer and will +restore STDOUT if the wrapped code dies. The difference is that in the +former, the original STDOUT can still be accessed by explicitly using it in a +C<print> statement (as C<print STDOUT ...>), whereas in the latter the meaning +of the STDOUT handle itself has temporarily been changed. + Portability issues: L<perlport/select>. =item select RBITS,WBITS,EBITS,TIMEOUT |