Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

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

by RonW (Parson)
on Oct 20, 2017 at 00:32 UTC ( [id://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 (Novice) 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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1201719]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (3)
As of 2024-04-19 01:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found