in reply to symbolic variables

If you are just being curious and playing with things, fine, but don't think of this as something you should do in production scripts. Outside obfuscation and golf consider symbolic references forbidden. You don't want to use them. You don't want to use them even by accident.

Replies are listed 'Best First'.
Re^2: symbolic variables
by Anonymous Monk on Jan 04, 2008 at 02:07 UTC
    yikes, i have to resort to them whenever i want to have "generic" logi +c that deals with a multitude of routines. i use symbolic references for : object methods dispatch tables and in most unit test scripts If you have a better alternative; i'll consider it!

    object methods : i use anonmyous routines for the methods that deal with scalar attributes.

    package <>; our $scalarMethods; @{ $scalarMethods } = qw( name ); foreach my $attributeScalar ( @{ $scalarMethods } ) { no strict "refs"; *$attributeScalar = sub { my $subName = $package . "::$attributeScalar"; if ($VRB) { print " $subName \n"; } my ($self) = shift; if (@_) { $self->{$attributeScalar} = shift; } return $self->{$attributeScalar}; } }

    dispatch tables : a generic manner to call routines in a package

    for ( $ndx=0; $ndx<=0; $ndx++ ) { no strict 'refs'; ($kgDATA,$pmDATA) = &{ "cktTmplt_utils::$SUB" }($ndx );

    unit test scripts : within the <>.t script

    # are package variables accessible ? no strict "refs"; foreach my $pkg ( @{ $filePackages } ) { for ( my $i=0; $i<=1; $i++ ) { ${ $pkg . "::VRB" } = $i; is( $i, ${ $pkg . "::VRB" }, "GLBL VAR : VRB" ); ${ $pkg . "::TST" } = $i; is( $i, ${ $pkg . "::TST" }, "GLBL VAR : TST" ); } ${ $pkg . "::VRB" } = 1; # no STDOUT durings tests ${ $pkg . "::TST" } = 1; # return data and don't execute } use strict "refs";

      Your first use to generate scalar methods is an OK use of symbolic references, because the way to create a named subroutine without using symbolic references is far more unwieldly:

      $::My::Package::{$attributeScalar} = sub {...};

      But why aren't you using Class::Accessor or any of the other modules which create such accessors for you?

      Using symbolic references in dispatch tables is convenient until you need to think about which subroutines are to be called dynamically and which not. Using hard references in a hash is self-documenting and more secure, and allows for renaming of the exported name:

      use vars qw(%user_methods); %user_methods = ( handle_foo => \&handle_foo, handle_bar => \&handle_bar, handle_baz => \&do_handle_baz, ); ... sub handle { my $data = shift; for my $filter (@_) { if (exists $user_methods{ $filter }) { $data = $user_methods{ $filter }->($data); } else { die "Unknown filter method '$filter'"; }; }; };

      Your third test will always succeed - you can always set global package variables. Also, I would ditch the C-style for loop in favour of:

      for my $i (0..1) {