epoch1 has asked for the wisdom of the Perl Monks concerning the following question:

Hi monks,

I'm just working my way through some Mojolicious tutorials. Can someone tell me what the => 'index' is doing after the anonymous subroutine please? I know it's telling Mojolicious to look for a template called 'index' but why is it written in this way rather than $c->render(template => 'index') inside the sub?

get '/' => sub my $c = shift; $c->render; } => 'index';

Thanks.

Replies are listed 'Best First'.
Re: Anonymous sub clarification (fat comma)
by LanX (Saint) on Jul 16, 2016 at 21:21 UTC
    The code you posted is broken and I am no Mojolicious user (yet), but...

    if you meant

    get '/' => sub { my $c = shift; $c->render; } => 'index';

    then it's the same as

    get ('/' , sub { ... } , 'index');
    ( sub body shortened for clarity )

    In other words, you are calling get with three parameters.

    Please look up "fat comma", i.e. => is just a , with stringification of the left hand side.

    In this case the => is just syntactic sugar, b/c no stringification happening here, but it reads better.

    Cheers Rolf
    (addicted to the Perl Programming Language and ☆☆☆☆ :)
    Je suis Charlie!

      Apologies for the missing brace. I am familiar with the fat comma I was just a bit confused by the way the code was written. Forehead slap moment, thanks for pointing out the obvious, it makes perfect sense now.
Re: Anonymous sub clarification
by AnomalousMonk (Archbishop) on Jul 16, 2016 at 22:42 UTC
Re: Anonymous sub clarification
by perlfan (Parson) on Jul 21, 2016 at 14:59 UTC
    As LanX said, it's just a parenthesis-less method call to "get". "=>" is often called a "fat comma" in Perl; but more over it's like passing an anonymous hash to the "get" method as implemented by Mojo.
    IOW, it's also equivalent to the following where "/" is the hash key and anonymous subroutine is the hash value:
    my $hash_ref = { '/' => sub {...} }; get($hash_ref);
    And for that matter,
    my $array_ref = [ '/', sub {...} ]; get($array_ref);
    Ultimately, you are associating the subroutine handler for the URL; in this case, "/".

      Hi perlfan,

      I just tested this with Mojolicious::Lite, and I had to dereference the hash/array with get(%$hash_ref); / get(@$array_ref); for it to work.

      Regards,
      -- Hauke D

        Cool, then I was close. I didn't test it and I don't use Mojo, but I think I made my point. Thanks!