in reply to modify variable on pass by value

merlyn may want to use a map() function, but a *really* good function handles scalars or arrays as inputs. To that end, here is an example that runs all the test cases I could think of.
#!/usr/local/bin/perl -w use strict; { test1 (); test2 (); test3 (); test4 (); } # # Uses a simple scalar # sub test1 { my $i = "Hello, World"; print "return - '", remove_caps ($i), "', \$i ='$i'\n"; } # # Simple scalar, result is set to a different variable # sub test2 { my $i = "Hello, World"; my $o = remove_caps ($i); print "return - \$i='$i', \$o='$o'\n"; } # # Pass a constant # sub test3 { print "constant - ", remove_caps ("Hello, World"), "\n"; } # # Operate on an array # sub test4 { my @iarray = ('Hello, World', 'Goodbye, Cruel World', 'Britney Spea +rs Sux'); my @oarray = remove_caps (@iarray); print "iarray = "; print "'$_', " foreach (@iarray); print "\n"; print "oarray = "; print "'$_', " foreach (@oarray); print "\n"; } # # Our humble little function # sub remove_caps { my @out = @_; tr/A-Z//d for (@out); return wantarray ? @out : $out[0]; }
--Chris

e-mail jcwren

Replies are listed 'Best First'.
RE (tilly) 2: modify variable on pass by value
by tilly (Archbishop) on Sep 11, 2000 at 23:02 UTC
    Actually scalars or arrays as inputs is handled if you can handle an array as input. What you wanted to do is properly handle scalars and arrays as desired output. (Which your function does.)

    That said I will admit to occasionally using the following hack that assumes that if you want a scalar back, you will always give me exactly one value. (I know, still I do it from time to time.)

    sub remove_caps; if (1 != @_) { return map {remove_caps($_)} @_; } my $str = shift; $str =~ tr/A-Z//d; return $str; }