Far too often I find myself having to check a bunch of input args for definedness. It's annoying, and this annoyance is almost definitely the reason for defined-or in Perl 5.10. However, I need a solution that works in older perls.
I came up with an idea that seems to work, but it works by messing about with @_. This makes me nervous. Anyone care to tell me why this code is dangerous?
I've got two routines to munge @_. One changes the source array, called fix_undef(), which seems like bad news to me. The other, called no_sfx_fix_undef() seems to be safe.
So, as far as my limited brain can tell, the second function is safe to use unless I plan on using @_ to modify the original routine's arguments. Any other gotchas I should know about?
use strict; use warnings; my @args = ( qw/fee fie foe fum/, undef, 1..3 ); print "No SFX\n", '-'x10, "\n"; Sub_With_NO_Side_Effects( @args ); print map { "'$_'\n" } @args; print "\nSFX\n", '-'x10, "\n"; Sub_With_Side_Effects( @args ); print map { "'$_'\n" } @args; sub Sub_With_NO_Side_Effects { &no_sfx_fix_undef; print "$_: '$_[$_]'\n" foreach 0..$#_; } sub Sub_With_Side_Effects { &fix_undef; print "$_: '$_[$_]'\n" foreach 0..$#_; } # This sub modifies the original calling function's variables. BAD NE +WS sub fix_undef { defined $_ or $_ = '' foreach @_; } # This seems to be ok... sub no_sfx_fix_undef { @_ = map { defined $_ ? $_ : '' } @_; } __END__ # OUTPUT No SFX ---------- 0: 'fee' 1: 'fie' 2: 'foe' 3: 'fum' 4: '' 5: '1' 6: '2' 7: '3' Use of uninitialized value in concatenation (.) or string at C:\temp\t +est.pl line 9. 'fee' 'fie' 'foe' 'fum' '' '1' '2' '3' SFX ---------- 0: 'fee' 1: 'fie' 2: 'foe' 3: 'fum' 4: '' 5: '1' 6: '2' 7: '3' 'fee' 'fie' 'foe' 'fum' '' '1' '2' '3'
TGI says moo
In reply to Messing with @_ by TGI
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |