Re: Modulino in Perl 6

2017-05-27 Thread Gabor Szabo
A bit late, but thanks to both of you :)
Gabor

On Tue, May 2, 2017 at 6:33 PM, Gianni Ceccarelli
 wrote:
> On Tue, 2 May 2017 17:02:40 +0200
> Gabor Szabo  wrote:
>> Is there some way in Perl 6 to tell if a file was executed directly or
>> loaded into memory as a module?
>
> One way that seems to work: define a ``sub MAIN``; it will be invoked
> when you execute the file as a program, but won't be touched if you
> load it as a module.
>
> Example: in file ``/tmp/x/Foo.pm6``::
>
>   class Foo {
> has $.value;
>   }
>
>   sub MAIN($value) {
> say Foo.new(:$value).value;
>   }
>
> then::
>
>   $ perl6 -I /tmp/x -e 'use Foo;say Foo.new(:value(5)).value'
>   5
>
>   $ perl6 /tmp/x/Foo.pm6
>   Usage:
> /tmp/x/Foo.pm6 
>
>   $ perl6 /tmp/x/Foo.pm6 12
>   12
>
> --
> Dakkar - 
> GPG public key fingerprint = A071 E618 DD2C 5901 9574
>  6FE2 40EA 9883 7519 3F88
> key id = 0x75193F88
>
> Leela: You buy one pound of underwear and you're on their list forever.


Re: Modulino in Perl 6

2017-05-02 Thread Gianni Ceccarelli
On Tue, 2 May 2017 17:02:40 +0200
Gabor Szabo  wrote:
> Is there some way in Perl 6 to tell if a file was executed directly or
> loaded into memory as a module?

One way that seems to work: define a ``sub MAIN``; it will be invoked
when you execute the file as a program, but won't be touched if you
load it as a module.

Example: in file ``/tmp/x/Foo.pm6``::

  class Foo {
has $.value;
  }

  sub MAIN($value) {
say Foo.new(:$value).value;
  }

then::

  $ perl6 -I /tmp/x -e 'use Foo;say Foo.new(:value(5)).value'
  5

  $ perl6 /tmp/x/Foo.pm6
  Usage:
/tmp/x/Foo.pm6 

  $ perl6 /tmp/x/Foo.pm6 12
  12

-- 
Dakkar - 
GPG public key fingerprint = A071 E618 DD2C 5901 9574
 6FE2 40EA 9883 7519 3F88
key id = 0x75193F88

Leela: You buy one pound of underwear and you're on their list forever.


Re: Modulino in Perl 6

2017-05-02 Thread Larry Wall
On Tue, May 02, 2017 at 05:02:40PM +0200, Gabor Szabo wrote:
: Using the caller() in Perl 5 one can figure out if the file was loaded
: as a module or executed as a script.
: 
: In Python one could check if __name__ is equal to "__main__".
: 
: Is there some way in Perl 6 to tell if a file was executed directly or
: loaded into memory as a module?
: 
: regards
: Gabor

If you write a MAIN sub, it should be called only if the file was executed
directly.

Larry


Modulino in Perl 6

2017-05-02 Thread Gabor Szabo
Using the caller() in Perl 5 one can figure out if the file was loaded
as a module or executed as a script.

In Python one could check if __name__ is equal to "__main__".

Is there some way in Perl 6 to tell if a file was executed directly or
loaded into memory as a module?

regards
Gabor