Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Opening a range of files with OPEN 1

Status
Not open for further replies.

johndoe3344

Programmer
Jul 5, 2007
13
US
I have a list of files named 'test1.txt', 'test2.txt', 'test3.txt'... etc to 'test35.txt'. I want perl to open test1, perform some operation, then do the same to test2, and so on.

This is my code fragment:
...
...
for ($a = 1; $a <=35; $a++) {
my $input = "test" . "$a" . ".txt";
open (FH_IN, $input) || die "Error: $!\n";
...
perform some function
...
}

But it gives me an error saying "String found where operator expected at..." Could anyone tell me what I did wrong?
 
There is nothing obvious in the code that you provided that would indicate that error.

If you have a line number, than just track down the error. that type of error is often an indication of a missing semicolon or some other rather simply coding mistake.

- Miller
 
Yeah, you were right Miller, sorry about that. I left out a few periods.
 
Couple of style and coding practice concerns:

1) Don't use $a or $b as variable names. Those are special variables reserved for sorting. Stick with $x, $y, $x or $i, $j, $k if you really want simple letter based variables. $i is a really good iterator.

2) Instead of C style loops, use a range for simple iteration. It's easier to read, and perl does this in a smart way so that it really is just an iterator.

Code:
[olive][b]for[/b][/olive] [url=http://perldoc.perl.org/functions/my.html][black][b]my[/b][/black][/url] [blue]$i[/blue] [red]([/red][fuchsia]1..35[/fuchsia][red])[/red] [red]{[/red]
	[black][b]my[/b][/black] [blue]$infile[/blue] = [red]"[/red][purple]test[blue]$i[/blue].txt[/purple][red]"[/red][red];[/red]
	[url=http://perldoc.perl.org/functions/open.html][black][b]open[/b][/black][/url][red]([/red]FH_IN, [blue]$infile[/blue][red])[/red] or [url=http://perldoc.perl.org/functions/die.html][black][b]die[/b][/black][/url] [red]"[/red][purple]Can't open [blue]$infile[/blue]: [blue]$![/blue][/purple][red]"[/red][red];[/red]

- Miller
 
And for iterating through the files, you could use glob:
Code:
for my $input ( glob 'test*.txt' ) {
  open (FH_IN, $input) || die "Error: $!\n";

   # etc.
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top