develooper Front page | perl.beginners | Postings from January 2002

foreach, while and flipping $_ !!!!!

Thread Next
From:
Parker, Robin
Date:
January 9, 2002 09:05
Subject:
foreach, while and flipping $_ !!!!!
Message ID:
DD2AB7991BC6D211988E00A024AC583B045D3339@exchange.nectech.co.uk
Hi all,

I have an array of filenames.

I want to read through each of the files.

I want to try and match a word at the beginning of the line, if the word is
not matched, I want to display an error and stop processing.

SO...


foreach @array_of_files
{
	unless (-r $_ && -w $_)
	{
		print"***Error : Cannot find file $_\n";
	}
	OPEN(FILE, $_) or die etc.......
	while (<FILE>)
	{
		/^\b$word\b/ && $wordfound++;
	}
	close (FILE);
	unless ($wordfound)
	{
		print"*** Error : word not found in file $_\n";
	}
	$wordfound = 0;
}


Now I understand that this won't work 'cause while will kill off foreach's
$_.  However, I tried something with a variable called $storage.

I added it in here...

	$storage = $_;
	while(<FILE>)

and here.....

	}
	$_ = $storage;
	close (FILE);

Bit of a grim solution I know.

This foreach loop was only part of the validation though.  If the validation
was successful, I then wanted to add a word to the end of each line with a
successful match.  So I wanted to use the same array of files, a foreach
loop and a while loop.

My second foreach loop then complains of my using uninitialised values.  So
I put in a print "@array_of_files\n"; after the first foreach loop.

It's empty.

OK, so while overwrote $_ but why does this delete the contents of
@array_of_files?

How do I stop while messing things up?  Something to do with 'local' isn't
it??

Oh, and if anyone can suggest any 'better' ways of doing the above, please
let me know.


Many Thanks,

Robin Parker
mailto:robin.parker@nectech.co.uk


Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About