Regex – Perl – Printing the next line

newlineperlregex

I am a noob Perl user trying to get my work done ASAP so I can go home on time today 🙂

Basically I need to print the next line of blank lines in a text file.

The following is what I have so far. It can locate blank lines perfectly fine. Now I just have to print the next line.

    open (FOUT, '>>result.txt');

die "File is not available" unless (@ARGV ==1);

open (FIN, $ARGV[0]) or die "Cannot open $ARGV[0]: $!\n";

@rawData=<FIN>;
$count = 0;

foreach $LineVar (@rawData)
    {
        if($_ = ~/^\s*$/)
        {
            print "blank line \n";
                    #I need something HERE!!

        }
        print "$count \n";
        $count++;
    }
close (FOUT);
close (FIN);

Thanks a bunch 🙂

Best Solution

open (FOUT, '>>result.txt');

die "File is not available" unless (@ARGV ==1);

open (FIN, $ARGV[0]) or die "Cannot open $ARGV[0]: $!\n";

$count = 0;

while(<FIN>)
{
    if($_ = ~/^\s*$/)
    {
            print "blank line \n";
            count++;
            <FIN>;
            print $_;

    }
    print "$count \n";
    $count++;
}
close (FOUT);
close (FIN);
  • not reading the entire file into @rawData saves memory, especially in the case of large files...

  • <FIN> as a command reads the next line into $_

  • print ; by itself is a synonym for print $_; (although I went for the more explicit variant this time...