Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:
To cut down on typing, I would like to change:
and still get the same results.showvar('$x',\$x) to showvar($x) showvar('@x',\@x) to showvar(@x) showvar('%x',\%x) to showvar(%x)
If we pass just a single argument named sigilVarname, say showvar(sigilVarname), what has got me stumped is how to extract the "Varname" part.
ie. showvar(@hello) sigil==@, Varname==hello
Any ideas on how to rewrite showvar() so that it works with one argument?
$x = qq(odd number of items kaboom); showvar('$x',\$x); # prints # $x SCALAR, 1 ITEM: # 'odd number of items kaboom' @x = qw(odd number of items kaboom); showvar('@x',\@x); # prints # @x ARRAY, 5 ITEMS: # 'odd' # 'number' # 'of' # 'items' # 'kaboom' %x = qw(odd number of items kaboom); showvar('%x',\%x); # prints # %x HASH, 3 KEY/VALUE PAIRS: # kaboom => ***EMPTY*** # odd => number # of => items sub showvar { # variables $, @, % local ($varname, $_) = @_; return print "\n*** One or two arguments are undefined ***\n" if ! +$_[0] or !$_[1]; my $type = ref; return print "\nVariable '$varname' is inconsistent with its refer +ence\n" if !$type; if (/SCALAR/) {print "$varname $type, "; show ($$_)} elsif (/ARRAY/) {print "$varname $type, "; show (@$_)} elsif (/HASH/) {print "$varname $type, "; showHASH (%$_)} else {print "$varname $type, is not of type SCALAR/ARRA +Y/HASH\n"} } sub show { my $len = scalar @_; my $plural = $len>1 ? 'ITEMS' : 'ITEM'; $_[0]="***EMPTY***" unless $_[0]; #avoid undef in mapping below print join "\n", "$len $plural:", map(" '$_'", @_), "------------ +\n\n"; } sub showHASH { . . # Avoid length error if hash value undef $hash{$_} = '***EMPTY***' if !defined $hash{$_}; . . # Pretty print print scalar keys %hash, " KEY/VALUE PAIRS: \n"; . . }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Source filter or PadWalker. Both are ugly
by imp (Priest) on Dec 08, 2006 at 09:36 UTC | |
by imp (Priest) on Dec 08, 2006 at 11:18 UTC | |
by Anonymous Monk on Dec 08, 2006 at 21:32 UTC | |
|
Re: How to extract the name of a variable?
by BrowserUk (Patriarch) on Dec 08, 2006 at 11:10 UTC | |
|
Re: How to extract the name of a variable?
by PreferredUserName (Pilgrim) on Dec 08, 2006 at 15:21 UTC |