Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

[OT]: Re^9: What's the right way to write a method which returns one line at a time from a file?

by AnomalousMonk (Archbishop)
on Nov 25, 2020 at 04:09 UTC ( [id://11124183]=note: print w/replies, xml ) Need Help??


in reply to Re^8: What's the right way to write a method which returns one line at a time from a file?
in thread What's the right way to write a method which returns one line at a time from a file?

Somewhat tangential, but a less messy, more readable and preferable (IMHO) version of this is:

return COND_A ? A : COND_B ? B : COND_C ? C : COND_D ? () : # returns undef or empty list per context die "unmatched case" ;


Give a man a fish:  <%-{-{-{-<

  • Comment on [OT]: Re^9: What's the right way to write a method which returns one line at a time from a file?
  • Select or Download Code

Replies are listed 'Best First'.
Re: [OT]: Re^9: What's the right way to write a method which returns one line at a time from a file?
by eyepopslikeamosquito (Archbishop) on Nov 26, 2020 at 09:52 UTC

    Yes, I agree. I especially like that there is only one return statement. In contrast, using multiple return statements violates the principle of DRY.

    Related items from Conway's Perl Best Practices, Chapter 6 (Control Structures):

    • Avoid cascading an if
    • Use table look-up in preference to cascaded equality tests
    • When producing a value, use tabular ternaries

    Conway recommends formatting tabular ternaries with the colon at the front, for example:

    # When their name is... Address them as... my $salute = $name eq $EMPTY_STR ? 'Customer' : $name =~ m/(.*), \s+ Ph[.]?D \z /xms ? "Dr $1" : $name ;
    because, if you squint, it looks like a lookup table, thus converting the notoriously impenetrable ternary syntax into a familiar and easy to understand lookup table.

    Update: Fixed typo in Conway's example my $salute statement above (removed extra ?). Thanks AnomalousMonk.

      # When their name is... Address them as... my $salute = $name eq $EMPTY_STR ? 'Customer' : $name =~ m/(.*), \s+ Ph[.]?D \z /xms ? "Dr $1" : ? $name ;

      One ? too many:

      Win8 Strawberry 5.8.9.5 (32) Thu 11/26/2020 5:03:36 C:\@Work\Perl\monks >perl -Mstrict -Mwarnings -l my $name = 'xyzzy'; my $salute = $name eq 'foo' ? 'Fooble' : $name eq 'bar' ? 'Barfly' : $name ; print $salute; ^Z xyzzy


      Give a man a fish:  <%-{-{-{-<

        Yes, I've corrected the offending node. Thanks.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (3)
As of 2024-04-20 01:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found