in reply to subroutine to search a pattern in a file
Also, as a general rule: if a subroutine opens a file, it should be responsible for closing it. A subroutine shouldn't leave a file open when it returns. Explicit closes are not required in the main program as all open file handles are closed when the main program exits. But if you pass a file name to something like my find_matching_lines() subroutine, you should close that file when you are finished with it, otherwise open the file the main program and pass a filehandle to the subroutine.
#!/usr/bin/perl -w use strict; print "*the backtick cat results:*\n"; print `cat /etc/filesystems`; #prints: # ext3 # ext2 # nodev proc # nodev devpts # iso9660 # vfat # hfs # hfsplus print "\n"; #spacer line my @catlines = `cat /etc/filesystems`; print "*the catlines array:*\n"; print @catlines; #prints same as backtick results above print "\n"; #spacer line my $file = '/etc/filesystems'; my $pattern = 'nodev'; my @lines= `grep $pattern $file`; print "*the grep backtick results:*\n"; print @lines; print "\n"; #spacer line #prints: # nodev proc # nodev devpts my @getlines = find_matching_lines($file,'ext'); print "*the getlines array*\n"; print scalar(@getlines), " lines found\n"; my $numlines = @getlines; print "number of lines = $numlines\n"; #same thing print "".@lines," lines found\n"; #the concatentation op "." forces sc +alar print @getlines; sub find_matching_lines { my ($file_name, $pattern)=@_; my @matches =(); open (my $in, '<', $file_name) or die "unable to open $file_name"; while (<$in>) { push (@matches,$_) if m/$pattern/; } close ($in); return @matches; } __END__ *the backtick cat results:* ext3 ext2 nodev proc nodev devpts iso9660 vfat hfs hfsplus *the catlines array:* ext3 ext2 nodev proc nodev devpts iso9660 vfat hfs hfsplus *the grep backtick results:* nodev proc nodev devpts *the getlines array* 2 lines found number of lines = 2 2 lines found ext3 ext2
|
|---|