Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

Re: searching a file

by jonadab (Parson)
on Jan 14, 2004 at 18:52 UTC ( #321335=note: print w/replies, xml ) Need Help??

in reply to searching a file

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$/

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (1)
As of 2023-06-05 20:43 GMT
Find Nodes?
    Voting Booth?
    How often do you go to conferences?

    Results (26 votes). Check out past polls.