Search code examples
program-entry-pointsubroutineraku

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?


Solution

  • 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