in reply to IO::Prompt -- why isn't this working (menu with hashref)?

IO::Prompt is returning an instance of IO::Prompt::ReturnVal, not a plain scalar value. Apparently this instance isn't boolean-ifying the way you expect (not that I disagree with your expectation after a quick initial read of the docs) and since it's not false you always get your first leg of your if executing.

Update: As a workaround you can explicitly stringify return $ans . "" or numify it return $ans + 0 and it should behave the way you want. Alternately explicitly test the value (e.g. if( shall_we() == 1 ) { ... } else { ... }).

Another way: Since you're using 5.10 there's always given:

use feature qw( switch say ); ## ... as your code ... given( shall_we() ) { when (1) { print "In the 'if' statement: yes, we shall.\n"; } when (0) { print "In the 'if' statement: no, we shant.\n"; } };

The cake is a lie.
The cake is a lie.
The cake is a lie.

Replies are listed 'Best First'.
Re^2: IO::Prompt -- why isn't this working (menu with hashref)?
by ikegami (Patriarch) on Jun 20, 2008 at 22:19 UTC

    Personally, I'd go with:

    sub shall_we { my $ans = prompt( "What'll it be?", -menu => { 'Yes, definitely.' => 1, 'No way.' => 0 }, ); return $ans ? 0+$ans : undef; }

    not that I disagree with your expectation after a quick initial read of the docs

    Or even after a thorough read. The returned object is not documented at all. From peeking at the source,

    • It returns whether prompt was successful (whatever that means) when used in boolean context.
    • It returns the answer as a string when used in string context.
    • It returns the answer as a number when used in numerical context.

    It has no methods.

    It has a very weird destructor that clobbers $_ if you don't do one of the above before the object is destroyed. That allows the following to work:

    sub shall_we { local $_; prompt( "What'll it be?", -menu => { 'Yes, definitely.' => 1, 'No way.' => 0 }, ); return $_; }

    Update: Fixed ... : ... : ... that should have been ... ? ... : ...