Daniel Mita
Daniel Mita

Reputation: 642

Can I capture the returned value of a routine used in RUN-MAIN?

I want a script to run a subroutine exported from a module, with the exported sub to be run as MAIN in the script. The subroutine does all that I want, except that it returns the result instead of printing it.

RUN-MAIN seems to achieve most of what I'm aiming for, but I'm not sure how to grab the returned value of the routine.

Is there a way I can capture the output of the routine given to RUN-MAIN to be printed? Is RUN-MAIN the right approach for this sort of thing?

Upvotes: 7

Views: 192

Answers (3)

Daniel Mita
Daniel Mita

Reputation: 642

Redispatch can be used within a wrapped routine to call the original. say can then be used on the result of the redispatch within the wrap. This will also generate usage from the original routine.

sub foo (
  $input #= The data we want
) {
  return $input;
}

&foo.wrap( sub (|) { callsame.say } );

RUN-MAIN &foo, Nil;

$ raku filename.raku

Usage:
  filename.raku <input>
  
    <input>    The data we want

Upvotes: 2

Daniel Mita
Daniel Mita

Reputation: 642

The following seems to accomplish what I intended (where foo is the target sub).

RUN-MAIN( &foo, Nil );

sub MAIN ( |c --> Nil ) {
  foo(|c).say;
}

EDIT: Unfortunately this solution is not ideal, as it runs &foo twice.

Upvotes: 2

wamba
wamba

Reputation: 4465

You could use the function composition operator infix:<∘> or infix:<o>

sub foo ($name, Int $n=1) { 
    "Hello $name\n" xx $n 
}; 
RUN-MAIN &say o &foo, Nil; #or &foo Ro &say

but unfortunately, it is changing the signature

sub foo ($name, Int $n=1) { 
    "Hello $name\n" xx $n 
};

say &foo.signature;
say (&foo Ro &say).signature;

so default USAGE message does not work.

Upvotes: 5

Related Questions