in reply to Declaring a code ref with arguments

have you ever tested your code? this is broken!!
however you should look at perldoc perlref on how to build code refs..
this is a working version:
#!/usr/bin/perl -w use strict; sub print_me { my $arg = shift || "Hello World!\n"; print $arg; } my %hash = (no_arg => sub { &print_me()}, with_arg => sub {&print_me("Hello again!\n")} ); $hash{no_arg}->(); $hash{with_arg}->();

Replies are listed 'Best First'.
Re: Re: Declaring a code ref with arguments
by !unlike (Beadle) on Aug 05, 2003 at 09:35 UTC

    The example I provided did not use strict. My apologies for that oversight. With that being the case the code worked fine (even with -w)

    Cheers

    !unlike

    I write my Perl code like how I like my sex: fast and dirty. ;)

Re: Re: Declaring a code ref with arguments
by cfreak (Chaplain) on Aug 05, 2003 at 13:35 UTC

    His argument passing is wrong but it sounds like you are saying that this:

    my %hash = ( foo =>\&do_foo, bar =>\&do_bar, );

    is wrong, (correct me if I'm misinterpreting your post) which I'm not sure where you find that in perlref as that works, even while using strict. To pass the arguments you can do this:

    $hash{foo}->('foo','bar','baz');
    Lobster Aliens Are attacking the world!
      no, at all, if you look carefully at what he posted you'll find this:
      %hash = {no_arg => \&print_me, with_arg => \&print_me("Hello World, again!\n" };
      as you can see he uses curly brackets to build a hash and lacks right parenthesis just after "Hello World, again!\n"
      what i say is that this code will never work (maybe is just a wrong trascription) and that you can't do
      bar =>\&do_bar("argument")
      so you have to do
      bar => sub { do_bar("argument") }
      that's all..
      update of course (foo => \&foo) with no arguments is perfectly legal..