Commit | Line | Data |
c07a80fd |
1 | package SelectSaver; |
2 | |
a399f54a |
3 | our $VERSION = '1.01'; |
b75c8c73 |
4 | |
c07a80fd |
5 | =head1 NAME |
6 | |
7 | SelectSaver - save and restore selected file handle |
8 | |
9 | =head1 SYNOPSIS |
10 | |
11 | use SelectSaver; |
12 | |
13 | { |
14 | my $saver = new SelectSaver(FILEHANDLE); |
15 | # FILEHANDLE is selected |
16 | } |
17 | # previous handle is selected |
18 | |
19 | { |
20 | my $saver = new SelectSaver; |
21 | # new handle may be selected, or not |
22 | } |
23 | # previous handle is selected |
24 | |
25 | =head1 DESCRIPTION |
26 | |
27 | A C<SelectSaver> object contains a reference to the file handle that |
28 | was selected when it was created. If its C<new> method gets an extra |
29 | parameter, then that parameter is selected; otherwise, the selected |
30 | file handle remains unchanged. |
31 | |
32 | When a C<SelectSaver> is destroyed, it re-selects the file handle |
33 | that was selected when it was created. |
34 | |
35 | =cut |
36 | |
37 | require 5.000; |
38 | use Carp; |
39 | use Symbol; |
40 | |
41 | sub new { |
42 | @_ >= 1 && @_ <= 2 or croak 'usage: new SelectSaver [FILEHANDLE]'; |
37ec1aec |
43 | my $fh = select; |
a399f54a |
44 | my $self = bless \$fh, $_[0]; |
37ec1aec |
45 | select qualify($_[1], caller) if @_ > 1; |
46 | $self; |
c07a80fd |
47 | } |
48 | |
49 | sub DESTROY { |
a399f54a |
50 | my $self = $_[0]; |
51 | select $$self; |
c07a80fd |
52 | } |
53 | |
54 | 1; |