Question

Would it be OK to keep the END block in this example, because nobody wants a broken terminal or shouldn't I put an END block in a module?

package My_Package;
use warnings;
use strict;
use Term::ReadKey;

sub _init_scr {
    my ( $arg ) = @_;
    $arg->{backup_flush} = $|;
    $| = 1;
    Term::ReadKey::ReadMode 'ultra-raw';
}

sub _end_win {
    my ( $arg ) = @_;
    print "\n\r";
    Term::ReadKey::ReadMode 'restore';
    $| = $arg->{backup_flush};
}

END {
    Term::ReadKey::ReadMode 'restore';
}

sub my_function {
    my $arg = {};
    _init_scr( $arg );
    while ( 1 ) {
        my $c = ReadKey 0;
        if ( ! defined $c ) {
            _end_win( $arg );
            warn "EOT";
            return;
        }
        next if $c eq "\e";
        given ( $c ) {
            when ( $c ge 'a' && $c le 'z' ) {
                print $c;
                $arg->{string} .= $c;
            }
            when ( $c eq "\cC" ) {
                _end_win( $arg );
                print STDERR "^C";
                kill( 'INT', $$ );
                return;
            }
            when ( $c eq "\r" ) {
                _end_win( $arg );
                return $arg->{string};
            }
        }
    }
}
Was it helpful?

Solution

If your module changes the terminal mode, then I would think the most polite thing to do would be for it to also install an END block to restore the terminal mode before the program exits.

OTHER TIPS

No, it's polite and expected that you put things back as you found them.

However, it's unwelcome to tidy up someone else's workspace unless you've been asked to do so.

That is, your END routine shouldn't run unless it has reason to do so, and your module probably ought to allow a developer to disable the automatic cleanup. (E.g., use My_Package qw(:no_auto_restore).)

Failing that, the POD ought to explicitly document that the module fiddles with a system resource upon exit.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top