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

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

Thread Next
Parker, Robin
January 9, 2002 09:05
foreach, while and flipping $_ !!!!!
Message ID:
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.


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 = $_;

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

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

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

Many Thanks,

Robin Parker

Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About