Hello hchana,
I would approach it like this:
#!/usr/bin/perl use strict; use warnings; use feature 'say'; my $file = 'file1.txt'; open (my $in, "<", $file) or die "Can't open $file: $!"; while (<$in>) { # assigns each line in turn to $_ chomp; next if /^\s*$/; # skip blank lines say "Line number: " . $. . " Content of line: " . $_; # print c +ontents of $_ line by line } close $in or warn "Can't close $file: $!"; __END__ $ perl test.pl Line number: 1 Content of line: ABS0056 Line number: 3 Content of line: ABS0057 Line number: 5 Content of line: ABS0058 Line number: 7 Content of line: ABS0059
You can read more here perlvar about the special variables e.g. $. that can help you to get the line number. I would suggest also to use chomp in general removes the new line character \n but it does more things than just that. Read the documentation for more information.
I would also skip the blank lines on your file since there is no need to process them, use next with a regular expression to detect the blank lines.
Update: You can also take advantage of the eof and simply pass all the files you want to process through the initialization of your script and you do not need to open and close the files this will be handled by the script for you. Sample of code with the use of Data::Dumper for complex data structures analysis:
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; use feature 'say'; my %hash; # reset line numbering on each input file while (<>) { chomp; next if /^\s*$/; # skip blank lines say "$.\t$_"; $hash{$ARGV}{$.} = $_; } continue { close ARGV if eof; # Not eof()! } print Dumper \%hash; __END__ $ perl test.pl file1.txt file2.txt 1 ABS0056 3 ABS0057 5 ABS0058 7 ABS0059 1 ABS0060 3 ABS0061 5 ABS0062 7 ABS0036 $VAR1 = { 'file2.txt' => { '7' => 'ABS0036', '5' => 'ABS0062', '1' => 'ABS0060', '3' => 'ABS0061' }, 'file1.txt' => { '5' => 'ABS0058', '7' => 'ABS0059', '1' => 'ABS0056', '3' => 'ABS0057' } };
Update2: Thanks to fellow monk 1nickt I remembered one of my favorite modules that is also able to parse files and do many more things IO::All. Sample of code:
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; use IO::All -utf8; # Turn on utf8 for all io my @lines = io('file.txt')->chomp->slurp; # Chomp as you slurp print Dumper \@lines; __END__ $ perl test.pl $VAR1 = [ 'line 1', 'line 2', 'line 3', 'line 4' ];
Hope this helps, BR.
In reply to Re: iterative foreach loop
by thanos1983
in thread iterative foreach loop
by hchana
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |