Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

comment on

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

Regarding in_list I personally would prefer either:

sub in_list {my $target=shift; return 0+grep { $_ eq $target } @_}

if you really care about the count (and want to use grep) or if you want fast then:

sub in_list {my $target=shift; $_ eq $target and return 1 for @_; retu +rn}

using the for modifier avoids creating and managing an extra scope (like grep,map and for statements) and avoiding the slice I think is more efficient. Afaik perl will have to create the sliced list first before iterating so you are really just copying the whole array which could get expensive for a large list.

Anyway heres an interesting/useful one :

sub find_first_index { my $target=shift; push @_,$target; my $i=0; $i++ while $_[$i] ne $target; return $i==$#_ ? undef : $i }

Which is a nice trick to reduce the cost of the tight loop. Dunno if more modern perls have been optimised enough that these tricks are unnecessary though. Its been a while since I benchmarked this stuff last.


---
demerphq

    First they ignore you, then they laugh at you, then they fight you, then you win.
    -- Gandhi



In reply to Re: Common Perl Idioms by demerphq
in thread Common Perl Idioms by eric256

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 wandering the Monastery: (8)
As of 2024-04-24 08:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found