[comp.lang.perl] what exactly does *foo = *bar'foo do.

muir@cae780.csi.com (David Muir Sharnoff) (04/23/91)

I would like to use *foo = $bar'foo to "import" variables into
packages.   However, I have a case where a variable seems to
loose its value and I want to know if my usage of aliasing 
could be causing problems like the one I'm having.

So, my question is: what are the gotchas of the following code:

	package baz;
	*bar = *main'bar;

I never set *bar to anything else and I only run the above command
once.

If using type globbing like I've been using it is safe, then could 
I use it to do fake structures:  (the following code is off-the-cuff, 
untried...)

    package struct;

    sub new
    {
	local($sd,$package) = @_;
	local($sym);

	unless (defined($symbol{$sd})) {
	    $sym = &gensym();
	    $symbol{$sd} = $sym;
	    $count{$sym} = 0;
	    $fields{$sym} = &uniq(sort(grep(s/[@$%]?(.)/$1/,split(' ',$sd))));
	}
	$sym = $symbol{$sd};
	&get($sym.$count{$sym},$package);
	return $sym.($count{$sym}++);
    }

    sub get
    {
	local($sym,$package);
	local($e);

	$package = 'main' unless $package;

	$e = "package $package;\n";

	for $f (split(/ /,$fields{$sym})) {
	    $e .= "*$f = *$sym'$f;\n";
	}
	eval $e;
	warn $@ if $@;
    }

    sub all
    {
	local($sd) = @_;
	local(@ret);
	local($sym);

	$sym = $symbol{$sd};
	for ($i = 0; $i <= $count{$sym}; $i++) {
	    push(@ret,$sym.$i);
	}
	return @ret;
    }

    package foo;

    $desc = '$a $b %c @c';
    $str = &struct'new($desc,'foo');
    $a = 1;
    $str = &struct'new($desc,'foo');
    $a = 2;
    $str = &struct'new($desc,'foo');
    $a = 3;
    for $x (&struct'all($desc)) {
	    &struct'get($desc,'foo');
	    print "$a\n";
    }

Thanks,

-Dave
-- 
David Muir Sharnoff.			"RISC is about one year ahead"
muir@csi.com				(415) 358-3664 (415) 644-0441
Comdisco Systems Inc.  919 East Hillsdale Blvd, Foster City, CA 94404