Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

I see two things in that code that I would suggest to improve:

  • Don't use eval - it allows execution of arbitrary Perl code, and getting the quoting of interpolated code right is tricky (try entering one double quote for $str), and so it should only be used sparingly. In this case it is not needed, just say: my $answer = $str =~ /$pattern/; - however note that then, your regexes should not be entered with the surrounding slashes.
    (If you do use eval someday, make sure to do proper error checking, as described e.g. here: something like eval "$code; 1" or warn "eval failed: $@";)
  • my $str = <STDIN>; and $pattern will have a newline on the end, which you should chomp off, e.g. chomp( my $str = <STDIN> );. See also the Basic debugging checklist, which suggests using a module like Data::Dumper or Data::Dump to look at what variables actually contain. If you use the former, I recommend setting $Data::Dumper::Useqq=1;.

In Perl, as opposed to Python's "there should be one - and preferably only one - obvious way to do it", TIMTOWTDI - There Is More Than One Way To Do It. While there are certainly 20 different ways to write the code you showed, don't worry about that too much - just keep your eye out for best practices like the ones I mentioned above, and otherwise enjoy learning Perl :-) We'll be happy to help.

Made a few minor edits.


In reply to Re: Idiomatic Perl? by haukex
in thread Idiomatic Perl? by thenextfart

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (4)
As of 2024-04-25 05:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found