This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Reduce SelectSaver memory footprint
[perl5.git] / lib / SelectSaver.pm
CommitLineData
c07a80fd
PP
1package SelectSaver;
2
26d58bfe 3our $VERSION = '1.03';
b75c8c73 4
c07a80fd
PP
5=head1 NAME
6
7SelectSaver - save and restore selected file handle
8
9=head1 SYNOPSIS
10
11 use SelectSaver;
12
13 {
2b393bf4 14 my $saver = SelectSaver->new(FILEHANDLE);
c07a80fd
PP
15 # FILEHANDLE is selected
16 }
17 # previous handle is selected
18
19 {
2b393bf4 20 my $saver = SelectSaver->new;
c07a80fd
PP
21 # new handle may be selected, or not
22 }
23 # previous handle is selected
24
25=head1 DESCRIPTION
26
27A C<SelectSaver> object contains a reference to the file handle that
28was selected when it was created. If its C<new> method gets an extra
29parameter, then that parameter is selected; otherwise, the selected
30file handle remains unchanged.
31
32When a C<SelectSaver> is destroyed, it re-selects the file handle
33that was selected when it was created.
34
35=cut
36
37require 5.000;
26d58bfe 38use Symbol q{qualify};
c07a80fd
PP
39
40sub new {
26d58bfe 41 @_ >= 1 && @_ <= 2 or do { require Carp; Carp::croak('usage: SelectSaver->new( [FILEHANDLE] )') };
37ec1aec 42 my $fh = select;
a399f54a 43 my $self = bless \$fh, $_[0];
37ec1aec
SB
44 select qualify($_[1], caller) if @_ > 1;
45 $self;
c07a80fd
PP
46}
47
48sub DESTROY {
a399f54a
AT
49 my $self = $_[0];
50 select $$self;
c07a80fd
PP
51}
52
531;