Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: sub-routines

by jreades (Friar)
on Nov 28, 2002 at 12:45 UTC ( #216293=note: print w/ replies, xml ) Need Help??


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.


Comment on Re: sub-routines
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://216293]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (8)
As of 2015-07-28 04:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (252 votes), past polls