Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: [Perl 6]: Small discoveries V, True / False / FileNotFound

by RonW (Parson)
on Oct 20, 2017 at 00:32 UTC ( #1201719=note: print w/replies, xml ) Need Help??


in reply to [Perl 6]: Small discoveries V, True / False / FileNotFound

Scalar::Util has dualvar which returns a scalar with both a numeric value and a string value.

In theory, could do:

# untested sub alsoslick() { if do-stuff { return dualvar 1, "SomeValue"; # or just a non-0 numeric value } else { return dualvar 0, "Some error message"; } } my $result = alsoslick; if 0+$result { process( '' . $result ); # or just $result if non-error result is +numeric } else { log-error( '' . $result ); }

(Not as clean as Perl6.)

Replies are listed 'Best First'.
Re^2: [Perl 6]: Small discoveries V, True / False / FileNotFound
by b2gills (Initiate) on Oct 24, 2017 at 23:19 UTC

    Perl 6 also has dual vars

    sub slick() { if do-stuff { return IntStr.new: 1, "SomeValue"; } else { return IntStr.new: 0, "Some error message"; } } my $result = slick; if +$result { process( ~$result ); } else { log-error( ~$result ); }

    I would not do this though, as you can pass around Failures just like any data type which but which act as undefined values.

    sub slick() { if do-stuff { return "SomeValue"; } else { fail "Some error message"; } } with slick() # is it defined -> $result { process $result } else -> $error { log-error $error.exception.message }

    Actually I would make it so that log-error accepts Failure objects, so that the .exception.message can be removed.

    proto sub log-error ( $ ) {*} multi sub log-error ( Str $message ) { say $message; # do the logging here } multi sub log-error ( Exception $exception ) { samewith $exception.message } multi sub log-error ( Failure $failure ) { samewith $failure.exception.message }

    You can also change out any method if you mixin a role.

    # this has the same effect as `but False` 'Some error message' but role { method Bool ( --> False ) {} }
      # this has the same effect as `but False` 'Some error message' but role { method Bool ( --> False ) {} }
      This is some serious voodoo. No wonder eval is warned of even more.


      holli

      You can lead your users to water, but alas, you cannot drown them.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1201719]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (9)
As of 2019-05-21 16:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you enjoy 3D movies?



    Results (136 votes). Check out past polls.

    Notices?
    • (Sep 10, 2018 at 22:53 UTC) Welcome new users!