Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: Re: Getting element of array with a match

by Arien (Pilgrim)
on Dec 24, 2002 at 04:18 UTC ( [id://222036]=note: print w/replies, xml ) Need Help??


in reply to Re: Getting element of array with a match
in thread Getting element of array with a match

The thing that bugs me most about that snippet is the match-chomp-split sequence. I prefer:

my $id = 1006; my $answer; for (@data) { last if ($answer) = /^\Q$id\E\s*,(.*)/o; }

— Arien

Update: Added /o and allowed for optional whitespace between id and comma per tachyon's worries below.

Replies are listed 'Best First'.
Re: Re: Re: Getting element of array with a match
by tachyon (Chancellor) on Dec 24, 2002 at 04:40 UTC

    Sure, that's the sort of way I would usually code it myself but you then have to (potoentially) explain how that single line works. There is also an implicit requirement in your code that the comma imediately follows the id as well as having no leading whitespace. All probably true but... You should have either used qr// or /o in your code BTW ;-)

    For those that are wondering the \Q...\E is the regex version of quotemeta which ensures that interpolated strings do not blow up your regex when they contain metachars. It is always sound practice to use \$Q$string\E in regexes.

    cheers

    tachyon

    s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

      (Also see update in my post above.)

      Sure, that's the sort of way I would usually code it myself but you then have to (potentially) explain how that single line works.

      The only thing that might have to be explained is that matching in a list context returns a list of the captured subexpressions.

      The fragment is idiomatic Perl, so somebody maintaining Perl code should at least be able to read it. I wouldn't think twice about writing it like this.

      — Arien

        I agree it is idiomatic Perl which is why I tend to avoid it in answers to Monks who have yet to grasp the basics of scalar and array context. *Your code is good code* and I personally prefer one line that gets the job done to half a page. I tend towards trying to tailor answers to what I percieve the level of the poster is so I don't have to bother explaining idioms in detail. That is unless I am in a hurry or a smartass mood when I will post brief stuff like Re: Re: Re: Looking Through Arrays?

        cheers

        tachyon

        s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (5)
As of 2024-03-28 16:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found