Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Mock STDIN

In Perl we can create a scalar variable containing some string and then we can open a file-handle for reading to “read” the content of that variable. We can then assign this file-handler to STDIN thereby allowing us to prepare what the rest of the code will see on the STDIN. Without the need for someone to type text and without the need to setup shell redirection.

use strict;
use warnings;

use Test::More;

use MyEcho qw(echo);

subtest test_echo => sub {
    my $input = "Hello";
    open my $stdin, '<', \$input  or die "Cannot open STDIN to read from string: $!";
    local *STDIN = $stdin;
    is echo(), 'olleH', 'echo works';
};

done_testing;