Try replacing the foreach loop with a while loop and just loop through the file. Something like this:
open(PAGES, "<pages.txt") || die $!;
my @filenames;
my @titles;
my @headings;
my @xstuff;
while (<PAGES>){
if (m/^\*{4}filename.ext\*{4}/) {
s/^\*{4}filename.ext\*{4}//;
chomp $_;
push(@filenames, $_);
}elsif (m/^\*{4}title\*{4}/) {
s/^\*{4}title\*{4}//;
chomp $_;
push(@titles, $_);
}elsif (m/^\*{4}heading\*{4}/) {
s/^\*{4}heading\*{4}//;
chomp $_;
push(@headings, $_);
}else {
push(@xstuff, $_);
}
}
close PAGES;
$_.=($=+(6<<1));print(chr(my$a=$_));$^H=$_+$_;$_=$^H;
print chr($_-39); # Easy but its ok.