in reply to Question on File Handler and Subroutines in Perl
Hello Anonymous Monk,
Perl is a well known scripting language that people choose to create 'Modules' that can assist you / us to reduce our lines of code to minimum. For example reading and loading all lines of a file in an array while removing the new line characters all in one line :)
One of the modules that I usually prefer to use is IO::All.
Then your task is simplified you just need to set the pattern to match (string or even multiple strings) and grep all elements that match your pattern using grep as you have done already :).
Small sample of code bellow:
#!/usr/bin/perl use strict; use warnings; use IO::All; use Data::Dumper; foreach my $file (@ARGV) { if ( -e $file ) { # double check existence my @lines = io($file)->chomp->slurp; # Chomp as you slurp if (my @matches = grep( /string/, @lines ) ) { print "Found in File: '$file':\n"; print Dumper \@matches; } } } __END__ $ perl test.pl a.txt b.txt c.txt Found in File: 'a.txt': $VAR1 = [ 'Line two interested, string' ]; Found in File: 'b.txt': $VAR1 = [ 'Line one interested, string', 'Line two interested, string' ]; __DATA__ $ cat a.txt b.txt c.txt Line one not interested Line two interested, string Line one interested, string Line two interested, string Line one not interested Line two not interested Line three not interested
You need to adjust it to your preferences but it should be close to what you want to achieve.
Update: I do not want to include the solution with the subroutine. There are several ways to put all your data together. One possible way I would suggest push. Give it a try and we will help you more if you get problems. After all programming / scripting is all about trying and failing until you get it right :)
Hope this helps, BR.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Question on File Handler and Subroutines in Perl
by Anonymous Monk on Mar 05, 2019 at 09:57 UTC | |
by thanos1983 (Parson) on Mar 05, 2019 at 10:32 UTC | |
by Anonymous Monk on Mar 06, 2019 at 02:01 UTC | |
by thanos1983 (Parson) on Mar 06, 2019 at 08:33 UTC | |
by Anonymous Monk on Mar 06, 2019 at 01:59 UTC |