in reply to Problem creating a function

It's the definition of your function that's not quite right -- in particular, how you're defining and accessing the parameters.

If you don't mind changing the variable's contents (i.e. "destructive cleaning"), then I would write the function like this:
sub cleaner { $_[0] =~ s/\n/<br>/g;; $_[0] =~ s/\t/ /g; }
Then you can call it like this:     cleaner( $dirty ); and that will change the value of the variable in the way you want.

However, I'd point out that that is a pretty uncommon way to use subroutines, althought there's nothing wrong with it. (Do it this way if it's appropriate.)

If you want to get a cleaned version of a value, without changing the original, I'd write it like this:
sub cleaner { local $_ = shift; s/\n/<br>/g;; s/\t/ /g; $_ }
You can call this one like this:     $clean = cleaner( $dirty );

jdporter
...porque es dificil estar guapo y blanco.

Replies are listed 'Best First'.
Re: Re: Problem creating a function
by tachyon (Chancellor) on Dec 25, 2002 at 09:51 UTC

    Modifying $_[0] is bad practice. Also what happens if you cleaner("This will crash your code with a can't modify read only value error")

    cheers

    tachyon

    s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

      Modifying $_[0] is bad practice.
      That's fine advice for newbies, but it's a white lie. Many languages support OUT parameters. Including Perl. At worst, it merits an encouragement to document the technique if used.
      what happens if you cleaner("This will crash your code with a can't modify read only value error")
      Perl helpfully tells you that you used the function incorrectly. So you got and fix your code. What's the big deal?

      jdporter
      ...porque es dificil estar guapo y blanco.

        What's the big deal.

        Here is an example. You are calling cleaner in some sub that is not always called in the CGI. You will get a 500 when you do and won't know about it until it happens because it is a runtime not compile time error. This script will crash 50% of the time:

        sub cleaner { $_[0] =~ s/foo/bar/; } if ( rand > 0.5 ) { cleaner('foo') } __DATA__ Modification of a read-only value attempted at script line 1. # someti +mes
        cheers

        tachyon

        s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print