rakudo icon indicating copy to clipboard operation
rakudo copied to clipboard

Reopening $*IN after getting EOF: free sub routine `get()` does not work with new `$*IN`

Open hakonhagland opened this issue 5 years ago • 4 comments

$ raku --version
Welcome to Rakudo(tm) v2020.11.
Implementing the Raku(tm) programming language v6.d.
Built on MoarVM version 2020.11.

Refer to this question on stackoverflow.com. Script 1.raku:

use v6;
print "Input line: ";
my $line = get;
if ($*IN.eof) {
    say "got EOF..";
    say "Reopening STDIN..";
    $*IN.close;
    $*IN = open "/dev/tty", :r, :chomp($*IN.chomp), :nl-in($*IN.nl-in),
        :encoding($*IN.encoding);
    my $line2 = get;
    say "Got line: {$line2}";
}
else {
    say "Not EOF, got line: {$line}";
}

When running the above script (entering CTRL-D on the prompt to create EOF):

$ 1.raku 
Input line: got EOF..
Reopening STDIN..
Cannot do 'get' on a handle in binary mode
  in block <unit> at ./1.raku line 12

so get() does not recognize the new $*IN ? However, if I change the line my $line2 = get; to my $line2 = $*IN.get; it works fine (no errors).

hakonhagland avatar Apr 21 '21 18:04 hakonhagland

I've just done a quick search of issues in this issue queue for "eof stdin". Two issues seem like they might be related (much more so the first one):

raiph avatar Apr 23 '21 12:04 raiph

BTW, in the above example if you assign the new handle to $*ARGFILES rather than $*IN it will work fine.

This is because get defaults its filehandle to $*ARGFILES so that it can deal with filenames supplied on the command line and the STDIN is only added to $*ARGFILES if there are no command line files when the mainline (or MAIN ) is executed. Assigning a re-opened handle to $*IN doesn't update $*ARGFILES and I'm not sure if there is an easy way of making that happen.

jonathanstowe avatar Apr 23 '21 13:04 jonathanstowe

FWIW, I have some things I want to try, but I'm procrastinating until after the 2021.4 release

lizmat avatar Apr 23 '21 13:04 lizmat

Rakudo 2023.05

When code is my $line = get reads first line only:

 ~ % raku hakon.p6  < alphabet.txt
Input line: Not EOF, got line: a

When code is my $line = $*IN.get, same:

~ % raku hakon.p6 < test_this_alpha.txt
Input line: Not EOF, got line: a

Without a file name waits for user input, then quits when received:

~ % raku hakon.p6 alphabet.txt
Input line: [# user types "a"]
Not EOF, got line: a

Send Ctrl-D in MacOS Terminal:

 ~ % raku hakon.p6                    
Input line: got EOF..
Reopening STDIN..

^C

jubilatious1 avatar Aug 31 '23 15:08 jubilatious1