Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: Idiomatic Perl?

by karthiknix (Sexton)
on Mar 20, 2018 at 15:45 UTC ( [id://1211348]=note: print w/replies, xml ) Need Help??


in reply to Idiomatic Perl?

Code seems to work, but it is better in PERL way as below.

use strict; use warnings; print "RegEx Engine 1.0\n________________\n"; print "Gimme a string: "; my $str = <STDIN>; print "Gimme a RegEx: "; my $pattern = <STDIN>; my $answer = ($str =~ /$pattern/); if ($answer) { print "Yes!"; } else { print "No."; } print "\nkthxbye\n";

Code Change at line "my $answer = ($str =~ /$pattern/);" will look for the pattern in $pattern in the string $str and will result in yes or no.

Replies are listed 'Best First'.
Re^2: Idiomatic Perl?
by hippo (Bishop) on Mar 20, 2018 at 16:34 UTC
    my $answer = ($str =~ /$pattern/); if ($answer) { print "Yes!"; } else { print "No."; }

    I think the ternary here would be even more idiomatic. You can replace those 6 lines with just one:

    print $str =~ /$pattern/ ? "Yes!" : "No.";

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (8)
As of 2024-04-25 11:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found