The use of $buffer also refers to the package variable. If you were to use strict you would get error messages like:
To get rid of these messages simply declare the variables at the beginning of your source file with either:Global symbol "$buffer" requires explicit package name at ... Global symbol "@output" requires explicit package name at ... Global symbol "%states" requires explicit package name at ...
ormy ($buffer, @output, %states);
if they need to be visible from outside the current package.our ($buffer, @output, %states);
Knowing this would be one thing, but what I really want is that the $buffer, the @input, the @output, and possibly even the $c would be data inside of a "Dfa" object,
To implement a more object-oriented approach like you might be inclined to do in Java, one usually would proceed like this:
package DFA; sub new { my $dfa = {}; bless $dfa, shift; # associates $dfa with the current package $dfa->{buffer} = ''; $dfa->{output} = []; # note: output is now an array reference $dfa->{states} = {}; # note: states is now a hash ref $dfa; # return the new object } ...
And here is an example of how a subroutine like argout would be implemented as method of the DFA class:
Also note how references to the variables $buffer and @output have changed.sub argout { my $dfa = shift; # $dfa here is equivalent to 'this' in Java my $temp = { type => 'ARG', value => $dfa->{buffer} }; $dfa->{buffer} = ''; push(@{$dfa->{output}}, $temp); } # example of constructing a DFA object and calling argout: my $dfa = DFA->new(); $dfa->argout();
This is just a very cursory overview of how to create a class in perl. For more details, see perldoc perlobj.
In reply to Re: Help with Variable Scope
by pc88mxer
in thread Help with Variable Scope
by tford
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |