Another way to do this is using grep:

# This code is untested. open PAGE, "$data_reg" or die "Can't open $data_reg: $!"; my @matchinglines = grep { $username eq (split "\t", $_)[0]; } <PAGE>; (print "<div>Unfortunately we cannot find reference to the username supplied.</div> <div>Please check with the webmaster of this site." and exit) unless @matchinglines; close PAGE;

The advantage of this way is that the code is shorter and less convoluted, thus easier to follow. The disadvantage is that it slurps the whole file into a list, so if the file is really huge it can be a memory overhead problem.

I can get round this by taking the 'else' statement out and doing (after close PAGE) [...] But I don't want to!

You didn't say why it is that you don't want to put the error-handling outside the loop. Did you realise that the way you have the code, the error handling happens after each line? So, for each line in the file that doesn't match the supplied username, the error condition would be triggered. (I say "would be", because the exit stops it after the first time.) Why is it that this is preferable to having the error condition checked for just once, after all the lines have been read?

Also, when you do check++, does your real code do something else, like save the line, or is it really just a check? Because, if it's really just a binary check, you could save time if you skip reading the rest of the lines. I don't know how much performance matters for your application, so this is just a thought.


$;=sub{$/};@;=map{my($a,$b)=($_,$;);$;=sub{$a.$b->()}} split//,".rekcah lreP rehtona tsuJ";$\=$ ;->();print$/

In reply to Re: searching a file by jonadab
in thread searching a file by Anonymous Monk

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



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.