Ken Slater wrote:
> From: Brian F. Yulga [mailto:byu...@langly.dyndns.org]

> On Wed, 2 Mar 2011, Matt wrote:

>> The easiest way in my opinion is to use the 'grep' function like
>> this:
>>
>> my $searchstring="whatever"; open CFG, '<', $_file || die("could
>> not open file: $_file!"); my @data=<CFG>; close CFG; if ( grep
>> /$searchstring/i, @data ) { print "$searchstring found\n"; }
>>
>
> This sorta worked.  Needed a minor change.
>
>> unless ( grep /$searchstring/i, @data ) {  print "$searchstring
>> not found\n";
>
> Thanks.
>
>
> My apologies if I'm beating a dead horse here, but I'm new to Perl
> and thought of a slightly different approach:
>
>
> my $searchrx = qr/whatever/;  # or q/whatever/ if you don't need
> regexp

 This is probably personal preference, but I prefer to provide a more
 meaningful name rather than using @ARGV. Plus you have lost the
 filename once you 'shifted' @ARGV in the open statement. May want to
 use the file name in the open error statement or later.

I agree with you, saving the filename to a variable is probably a better practice, in general. In this context it wasn't specified that it was needed later, so I opted to just 'shift' it to use once.

 Also, I would not use the '/' as your quote delimiter - that's too
 recognizable as being used as the pattern match delimiter. Use actual
 double quotes (") unless there are double quotes in the string - also
 less typing. Instead of '/' may want to use '{' and '}' if using qq
 (see perldoc perlop, Quote and Quote-like Operators).

Good point. I started using generic quotes almost exclusively when I discovered that they avoided some of the possible shell-interpolation issues that arise when executing perl "one-liners". I've probably taken it too far. I can see that '/' is not a great idea. Besides '{' and '}' as quote delimiters, do you think it's generally tolerated to use '(', ')', '[', ']' ?


 my $fileName = shift @ARGV or die "You did not specify a
 filename\n";
> @ARGV or die qq/you didn't specify a filename\n/;

 Use lexical variable for filehandle. Makes things easier - such as
 passing to a function.

 open my $FH,'<', $fileName or die "Error opening $fileName: $!\n";
> open FH, q/</, shift @ARGV or die qq/file open error: $!/;

Okay, I'll work on breaking that habit. My first "lessons" in Perl used the "open FH" convention, and I just got used to it.

 The join is unnecessary, set the input_record_separator ($/) to undef
 or use a local copy of $/ (see perldoc perlvar). If this is
 undefined, the entire file will be read into a variable.


Oh, I totally forgot about the input_record_separator ( $/ )... That's WAY better (actually when I wrote the 'join', I was thinking that I shouldn't need to do it that way!)

Thanks much for the suggestions,

Brian


--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to