Hi, Monks: I used to use c++, but beginner for perl. I want to create a singleten class with a bunch of attributes and methods but didn't know how.
use strict; use warnings; package MyConfig; use XML::Simple; my $singleton; my $XMLfile_name=""; my @hostList = (); sub new { my $class = shift; #create singleton $singleton ||= bless {}, $class; #Error here: Useless use of hash element in void context $singleton->{$XMLfile_name}=$_[0]; return $singleton; } sub loadConfig{ my $self=shift; my $xml = XML::Simple->new; my $config = $xml->XMLin($file_name, ForceArray => [ 'host', 'component' ]) or die$!; my $index=0; while($config->{host}->{component}->[$index++]) { push @hostList, $config->{host}->{component}->[0]->{component_name}; } } 1;
The XML structure is like:
<root> <component component_name="n1" /> <component component_name="n2" /> <component component_name="n3" /> </root>
I call code as:
use strict; use MyConfig; my $CONFIG = "somefile.xml"; &main; sub main { my configReader = MyConfig->new( $CONFIG ); configReader->loadConfig; }
As you see, I didn't know how to create and use what we say member variable in c++. The $XMLfile_name and the @hostList here is using as member variables. @hostList used for holding results parsed from the XML file.
Another question: In the new method, as I read package method always put the invoker as the first argument. I suppose 'invoker' for new() means the class MyConfig and return an instance after blessed; And the 'invoker' for loadConfig seems change to be an instance, seems the $self by te first default argument is an instance not the class any more. But as I know the 'new' is an ordinary method as others, not a keywords, why they behaves different?
The last question:I don't think I made my while condition correct. How can I deal with the while index simply using $_? Thanks a lot in advance!!
In reply to how to make a package variable as c++ by anaconda_wly
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |