http://www.perlmonks.org?node_id=216293


in reply to sub-routines

The quick answer is that you only return $line and not the entire file, but there are some other significant issues with the code. You also reset the variable $line twice within the subroutine, and it's not scoped properly.

Although you can sort of get away with what you're doing here (calling a file within a subroutine that isn't properly scoped to that subroutine), it's hard to read and prone to bugs.

A better way to think about this is to address the fact that the subroutine operates on a single line at a time, and not the entire file.

Don't shoehorn in the file operation as well since it doesn't make logical sense. Instead, pass the subroutine a line at a time since that is its logical 'scope' (as distinct from the lexcial scope).

open (IN "<...") or die("..."); open (OUT ">...") or die("..."); my $line; while ($line = <IN>) { print OUT replace($line); # you could drop the $line and use $_ } close IN; close OUT; exit 0; sub replace { my $line = shift; #skip the comp since you're printing out newlines $line =~ s/data|=|detector//g; return $line; }

I think that'll do it.