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


in reply to Re^2: Print HTML form to file using CGI.pm save method
in thread Print HTML form to file using CGI.pm save method

One thing some beginning programmers (usually of the procedural discipline) often miss is that functions are supposed to be like their mathematical definition, f(x) = expr. That is, they generally take a value or three as input, and return a value as output. They aren't supposed to access variables outside their scope ("globals", as we call them in the programming world). Of course, there are half a dozen of exceptions to that rule.

I can see that you are accessing the variables $clrNr, $tempfil, and $qry. I'll trust that the latter two are OK as globals, but the first one probably isn't. Here's how we pass it to your function:

sub kundNytt { my ($trans) = @_; # do something with $trans }

And here is how you call it.

$clrNr = 42; kundNytt($clrNr);

Your code, as it is currently, is fragile, and relies on $clrNr being correctly set before the function is called. It will break sooner or later. Seeing that functions are akin to their mathematical definition helps produce code that is much easier to understand and more reliable.

Ah, this is probably covered in pretty much every programming book written in the last three decades. You could read one :)