Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!uwm.edu!bionet!agate!usenet.ins.cwru.edu!ncoast!allbery From: allbery@NCoast.ORG (Brandon S. Allbery KB8JRR/AA) Newsgroups: comp.lang.perl Subject: Re: file append/read (+>>) Message-ID: <1991Apr3.030016.19788@NCoast.ORG> Date: 3 Apr 91 03:00:16 GMT References: <6086@beryl12.UUCP> Reply-To: allbery@ncoast.ORG (Brandon S. Allbery KB8JRR/AA) Followup-To: comp.lang.perl Distribution: comp Organization: North Coast Public Access Un*x (ncoast) Lines: 38 As quoted from <6086@beryl12.UUCP> by mostek@motcid.UUCP (Frank B. Mostek): +--------------- | Also, is there a way to grep a file within perl? Perl's grep needs a | list, I currently use system("grep...") which is much slower. I just | need to know if an expression occurs in a file. Is there an elegant | way to do this using Perl's constructs? +--------------- open(F,$file) || die "can't open $file: $!\n"; print grep(/re/, ); # being in an array context, it puts the file into a temporary array and # then greps that. This behaves like grep(1) with one file argument and no # other options. # To simply determine the existence of an expression in a file: $found = grep(/re/, ); # grep returns an array of all the "true" values (the lines on which the /re/ # succeeded); in a scalar context, an array produces the length of the array, # which is 0 if no line contains /re/. Since 0 is false and non-0 is true, # this works as we expect. If you want to use the grep as an expression and # it might accidentally be taken as an array value, use "scalar" or one of # the other tricks (concatenate the empty string, add 0, etc.) to force a # scalar context. # Be warned that either of these on a large file will take a LOT of memory. # If this is a problem, do it one line at a time: $found = 0; $found += /re/ while $_ = ; # or while () { $found += /re/; } close(F); -- Me: Brandon S. Allbery Ham: KB8JRR/AA on 2m, 220, 440, 1200 Internet: allbery@NCoast.ORG (QRT on HF until local problems fixed) America OnLine: KB8JRR // Delphi: ALLBERY AMPR: kb8jrr.AmPR.ORG [44.70.4.88] uunet!usenet.ins.cwru.edu!ncoast!allbery KB8JRR @ WA8BXN.OH