sample.cpp
struct InstanceConfig_1
{
unsigned int m_Ssn;
char m_StackName [31];
unsigned int m_MaxMsgs;
char m_LogicalName [29];
};
struct InstanceConfig_2
{
unsigned int m_Ssn;
char m_StackName [31];
unsigned int m_MaxMsgs;
char m_LogicalName [29];
};
Compare.pl
use strict;
use warnings;
use Data::Dumper;
my $each;
open FILE, "sample.cpp";
my @inst1 = ();
my @inst2 = ();
my $start = 0;
foreach $each (<FILE>)
{
chomp $each;
if($each =~ /^[ \t]*$/) # skip empty lines
{
next;
}
if($each =~ /{/)
{
$start = 1;
}
elsif($each =~ /}/)
{
$start = 0;
last;
}
elsif($start > 0)
{
$each =~ s/^\s+//; # remove leading space
$each =~ s/\s+$//; # remove trailing space
$each =~ s/\s+/ /g; # replace multiple space with single space
push(@inst1, $each);
}
}
foreach $each (<FILE>)
{
chomp $each;
if($each =~ /^[ \t]*$/) # skip empty lines
{
next;
}
if($each =~ /{/)
{
$start = 1;
}
elsif($each =~ /}/)
{
$start = 0;
last;
}
elsif(1 == $start)
{
$each =~ s/^\s+//; # remove leading space
$each =~ s/\s+$//; # remove trailing space
$each =~ s/\s+/ /g; # replace multiple space with single space
push(@inst2, $each);
}
print $each;
}
print Dumper(\@inst1);
print Dumper(\@inst2);
output
$VAR1 = [
'unsigned int m_Ssn;',
'char m_StackName [31];',
'unsigned int m_MaxMsgs;',
'char m_LogicalName [29];'
];
$VAR1 = [];
why @inst2 is empty?
my @lines = <FILE>;and then loop over the array withforeach $each (@lines)<FILE>inforeach $each (<FILE>)is not retrieving the lines one by one. It is executed once, at the start of the loop, returning a list of all the lines. The loop then iterates over that list.lasting out of the loop doesn't undo the "read all lines" operation that happened before the loop started.