简体   繁体   中英

How to pipe in a string to a Raku program?

foo.raku :

#! /usr/bin/env raku
use v6.d;

sub MAIN (Str $some-text = $*IN.slurp, Bool :$verbose) {
    say "Your text:" if $verbose;
    say $some-text;
}          

When I run it

~% echo "Hello World" | ./foo.raku --verbose

I get:

Your text:

How do I write the Signature in MAIN so that it captures piped-in strings?

In short: you currently can not.

I think https://docs.raku.org/language/variables#$*ARGFILES tells the reason in a roundabout way.

I see two ways around this:

Make the first positional optional without a default, and check for definedness later

sub MAIN (Str $some-text?, Bool :$verbose) {
    say "Your text:" if $verbose;
    say $some-text // $*IN.slurp;
}

Grab the contents of $*IN before MAIN gets executed, and use that as the default:

my $default = $*IN.slurp;
sub MAIN (Str $some-text = $default, Bool :$verbose) {
    say "Your text:" if $verbose;
    say $some-text;
}

In any case, using $*IN.slurp has its disadvantages if the script is called without being piped some input. It will just wait for the user to type in something without prompt. Which could be interpreted as hanging. So you probably want to add a check using https://docs.raku.org/routine/t#(IO::Handle)_method_t somehow, if at least to provide some visual feedback:

say "Type input, then ^D" if $*IN.t;
my $default = $*IN.slurp;
sub MAIN (Str $some-text = $default, Bool :$verbose) {
    say "Your text:" if $verbose;
    say $some-text;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM