anaconda_wly has asked for the wisdom of the Perl Monks concerning the following question:
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!!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: how to make a package variable as c++
by aitap (Curate) on Nov 04, 2012 at 09:37 UTC | |
by Anonymous Monk on Nov 04, 2012 at 09:44 UTC | |
by Anonymous Monk on Nov 04, 2012 at 09:49 UTC | |
by anaconda_wly (Scribe) on Nov 04, 2012 at 09:53 UTC | |
|
Re: how to make a package variable as c++
by tobyink (Canon) on Nov 04, 2012 at 10:33 UTC | |
by anaconda_wly (Scribe) on Nov 04, 2012 at 11:27 UTC | |
by anaconda_wly (Scribe) on Nov 04, 2012 at 11:49 UTC |