[32194] in Perl-Users-Digest

home help back first fref pref prev next nref lref last post

Perl-Users Digest, Issue: 3459 Volume: 11

daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Fri Jul 29 18:09:41 2011

Date: Fri, 29 Jul 2011 15:09:05 -0700 (PDT)
From: Perl-Users Digest <Perl-Users-Request@ruby.OCE.ORST.EDU>
To: Perl-Users@ruby.OCE.ORST.EDU (Perl-Users Digest)

Perl-Users Digest           Fri, 29 Jul 2011     Volume: 11 Number: 3459

Today's topics:
        data to hash <nospam.gravitalsun@hotmail.com.nospam>
    Re: Does "prove" have a way of running pre-test initial <news@lawshouse.org>
    Re: Generating an anonymous reference to an OO method (Randal L. Schwartz)
    Re: Generating an anonymous reference to an OO method <rweikusat@mssgmbh.com>
    Re: Generating an anonymous reference to an OO method <uri@StemSystems.com>
    Re: Generating an anonymous reference to an OO method <rweikusat@mssgmbh.com>
    Re: Generating an anonymous reference to an OO method (Randal L. Schwartz)
    Re: Generating an anonymous reference to an OO method <rweikusat@mssgmbh.com>
    Re: Generating an anonymous reference to an OO method <rweikusat@mssgmbh.com>
    Re: Search and replace question <uri@StemSystems.com>
    Re: XML::Simple drives me mad <kkeller-usenet@wombat.san-francisco.ca.us>
    Re: XML::Simple drives me mad <news@lawshouse.org>
    Re: XML::Simple drives me mad <RedGrittyBrick@spamweary.invalid>
    Re: XML::Simple drives me mad <uri@StemSystems.com>
    Re: XML::Simple drives me mad <derykus@gmail.com>
    Re: XML::Simple drives me mad <kkeller-usenet@wombat.san-francisco.ca.us>
    Re: XML::Simple drives me mad <klaus03@gmail.com>
        Digest Administrivia (Last modified: 6 Apr 01) (Perl-Users-Digest Admin)

----------------------------------------------------------------------

Date: Sat, 30 Jul 2011 00:27:48 +0300
From: George Mpouras <nospam.gravitalsun@hotmail.com.nospam>
Subject: data to hash
Message-Id: <j0v8kj$ocs$1@news.ntua.gr>

Here is something I think it is interesting.
Converts data (e.g. sql queries) to trees for a user driven virtual file 
system






#!/usr/bin/perl

my %hash  =	();
my @array =	(
		[ 'a0' , 'a1' , 'a2' , 'a3' , 'a4' , 'a5' , 'a6' ],
		[ 'b0' , 'b1' , 'b2' , 'b3' , 'b4' , 'b5' , 'b6' ],
		[ 'c0' , 'c1' , 'c2' , 'c3' , 'c4' , 'c5' , 'c6' ],
		[ 'd0' , 'd1' , 'd2' , 'd3' , 'd4' , 'd5' , 'd6' ],
		[ 'e0' , 'e1' , 'e2' , 'e3' , 'e4' , 'e5' , 'e6' ],
		);

foreach (@array) {
Stream_of_data_to_dynamic_hash( $_ , [1,0,5], \%hash )
}

use Data::Dumper;print Data::Dumper::Dumper(\%hash);






# Stream_of_data_to_dynamic_hash( INPUT LIST REF, REF COLUMNS TO BECOME 
KEYS, TARGET HASH REF )
#
# Convert a stream of data to a hash with user defined keys hierarchy.
#
#	my %MyDB = ();
#	Stream_of_data_to_dynamic_hash( ['John','Brown',11,'N. York'] , [3, 2] 
, \%MyDB );
#	Stream_of_data_to_dynamic_hash( ['May' ,'Green',72,'N. York'] , [3, 2] 
, \%MyDB );
#	print %MyDB;
#
sub Stream_of_data_to_dynamic_hash
{
my @data	= $#{$_[0]} != -1 ? @{$_[0]} : return;
my @Keys	= $#{$_[1]} != -1 ? @{$_[1]} : 0;
my $Ref		= $_[2];
my $LastKey	= $data[$Keys[-1]];
my %Del		= ();

	for (my $i=0; $i < $#Keys; $i++)
	{	
	die "At second argument, the ".(1+$i)." element with value 
\"$Keys[$i]\" is bigger than the total number $#data (0 offset) of items 
of the 1st input list argument\n" if $Keys[$i] > $#data;
	$Ref->{ $data[$Keys[$i]] } = {} unless ref $Ref->{ $data[$Keys[$i]] };
	$Ref = $Ref->{ $data[$Keys[$i]] }
	}

die "At second argument, the ".(1+$#Keys)." element with value 
\"$Keys[$#Keys]\" is bigger than the total number $#data (0 offset) of 
items of the 1st input list argument\n" if $Keys[$#Keys] > $#data;
foreach (reverse sort @Keys) { exists $Del{$_} ? ( next ):( $Del{$_}='' 
, splice(@data, $_, 1) ) } # Exclude used keys from the values
push @{$Ref->{$LastKey}}, [@data]
}


------------------------------

Date: Fri, 29 Jul 2011 16:44:22 +0100
From: Henry Law <news@lawshouse.org>
Subject: Re: Does "prove" have a way of running pre-test initialization?
Message-Id: <7-ydnfVp_p3KSK_TnZ2dnUVZ8v2dnZ2d@giganews.com>

On 29/07/11 15:55, George Mpouras wrote:
> `rm -rf dir/*`
> `tar  xf foo.tar -C dir`

Well, of course.  Forgive me for not writing that I'd considered that 
rather obvious solution.

The problem with it is this: into which test module should I put it? 
"prove" can run tests in different orders; it can omit tests either 
automatically or on demand; and you can tell it to run particular tests. 
  I want something that will run the initialisation under all of those 
circumstances and more.

ExtUtils::MakeMaker will automatically execute "test.pl" in the current 
directory before it runs the tests; that's the behaviour I want to get 
out of "prove".

But if I have to write a program called 'dotests' and make it execute 
those two commands of yours and then prove, so be it.  Actually, now 
that I come to think of it, I can make it tear down the test environment 
at the end of testing, which might be a bonus.

-- 

Henry Law            Manchester, England


------------------------------

Date: Fri, 29 Jul 2011 09:30:23 -0700
From: merlyn@stonehenge.com (Randal L. Schwartz)
Subject: Re: Generating an anonymous reference to an OO method
Message-Id: <86sjppnj6o.fsf@red.stonehenge.com>

>>>>> "Rainer" == Rainer Weikusat <rweikusat@mssgmbh.com> writes:

>> my $maker = do {
>> my $class = "Digest::MD5"; # or however you want to determine this
>> sub { return $class->new->add(@_) };
>> };
>> 

Rainer> Provided that $class never changes, an alternative with some possibly
Rainer> desirable technical properties (such as not tying up the scalar $class
Rainer> in order to determine a value which never changes during invocation)
Rainer> would be (not actually compiled):

Rainer> 	eval("sub { return $class->new->add(".'@_); }');

If $class never changes, just hardwire it.  DON'T USE EVAL-STRING.
DON'T USE EVAL-STRING.

  my $maker = sub { return Digest::MD5->new->add(@_) };

And not sure if I covered this already, but DON'T USE EVAL-STRING.

If you don't know why I'm saying this so strongly, then it applies
doubly to you. :)

print "Just another Perl hacker,"; # the original

-- 
Randal L. Schwartz - Stonehenge Consulting Services, Inc. - +1 503 777 0095
<merlyn@stonehenge.com> <URL:http://www.stonehenge.com/merlyn/>
Smalltalk/Perl/Unix consulting, Technical writing, Comedy, etc. etc.
See http://methodsandmessages.posterous.com/ for Smalltalk discussion


------------------------------

Date: Fri, 29 Jul 2011 18:18:02 +0100
From: Rainer Weikusat <rweikusat@mssgmbh.com>
Subject: Re: Generating an anonymous reference to an OO method
Message-Id: <871ux980qd.fsf@sapphire.mobileactivedefense.com>

merlyn@stonehenge.com (Randal L. Schwartz) writes:
>>>>>> "Rainer" == Rainer Weikusat <rweikusat@mssgmbh.com> writes:
>
>>> my $maker = do {
>>> my $class = "Digest::MD5"; # or however you want to determine this
>>> sub { return $class->new->add(@_) };
>>> };
>>> 
>
> Rainer> Provided that $class never changes, an alternative with some possibly
> Rainer> desirable technical properties (such as not tying up the scalar $class
> Rainer> in order to determine a value which never changes during invocation)
> Rainer> would be (not actually compiled):
>
> Rainer> 	eval("sub { return $class->new->add(".'@_); }');
>
> If $class never changes, just hardwire it.

If it never changes AFTER its value was determined, obviously ...

> DON'T USE EVAL-STRING.
> DON'T USE EVAL-STRING.

 ... then you can effectively hardwire it by using eval to run the Perl
compiler to create suitable subroutine at runtime. 

>
>   my $maker = sub { return Digest::MD5->new->add(@_) };
>
> And not sure if I covered this already, but DON'T USE EVAL-STRING.
>
> If you don't know why I'm saying this so strongly, then it applies
> doubly to you. :)

I really don't know why you think that running the Perl compiler from
within Perl-code in order to create new compiled code should be
avoided. I'll happily learn the reason for that, though.


------------------------------

Date: Fri, 29 Jul 2011 13:24:15 -0400
From: "Uri Guttman" <uri@StemSystems.com>
Subject: Re: Generating an anonymous reference to an OO method
Message-Id: <878vrhgfuo.fsf@quad.sysarch.com>

>>>>> "RW" == Rainer Weikusat <rweikusat@mssgmbh.com> writes:

  RW> I really don't know why you think that running the Perl compiler from
  RW> within Perl-code in order to create new compiled code should be
  RW> avoided. I'll happily learn the reason for that, though.

you have shown a massive unwillingness to learn from anyone here. why
should that change now? eval string is nasty and evil for many reasons,
most of them pretty obvious too. the first one is it is rarely needed as
you can almost always do things without it. of course that won't satisfy
you. i won't bring up the other reasons as i will leave them as an
exercise for you. see if you can actually second guess your own thought
processes and see why your view is very wrong about string eval. this
will be amusing to see your head go pop! :)

uri

-- 
Uri Guttman  --  uri AT perlhunter DOT com  ---  http://www.perlhunter.com --
------------  Perl Developer Recruiting and Placement Services  -------------
-----  Perl Code Review, Architecture, Development, Training, Support -------


------------------------------

Date: Fri, 29 Jul 2011 18:34:01 +0100
From: Rainer Weikusat <rweikusat@mssgmbh.com>
Subject: Re: Generating an anonymous reference to an OO method
Message-Id: <87wrf16lfa.fsf@sapphire.mobileactivedefense.com>

"Uri Guttman" <uri@StemSystems.com> writes:
>>>>>> "RW" == Rainer Weikusat <rweikusat@mssgmbh.com> writes:
>
>   RW> I really don't know why you think that running the Perl compiler from
>   RW> within Perl-code in order to create new compiled code should be
>   RW> avoided. I'll happily learn the reason for that, though.
>
> you have shown a massive unwillingness to learn from anyone here.

I have (and do) show 'a massive unwillingness' to accept anything from
anyone without complete information (IOW not "I know something you
don't know") and a sensible reason for it.

> why should that change now? eval string is nasty and evil for many reasons,
> most of them pretty obvious too.

"I know something you don't know" (and I'm not going to tell it to
you, either).

> the first one is it is rarely needed as you can almost always do
> things without it.

eval with a string argument can be used to create compiled code at run
time. Insofar you have a specific reason why you think something's
wrong with that (and this specific reason happens to make sense), I
will, as I wrote, happily listen to it and accept it.

As for you usual idle boasting and insults, 

> of course that won't satisfy you. i won't bring up the other reasons
> as i will leave them as an exercise for you. see if you can actually
> second guess your own thought processes and see why your view is
> very wrong about string eval. this will be amusing to see your head
> go pop! :)

you are free to stick them somewhere where the sun doesn't shine.


------------------------------

Date: Fri, 29 Jul 2011 10:30:21 -0700
From: merlyn@stonehenge.com (Randal L. Schwartz)
Subject: Re: Generating an anonymous reference to an OO method
Message-Id: <86bowdngeq.fsf@red.stonehenge.com>

>>>>> "Rainer" == Rainer Weikusat <rweikusat@mssgmbh.com> writes:

Rainer> ... then you can effectively hardwire it by using eval to run the Perl
Rainer> compiler to create suitable subroutine at runtime. 

You can just as easily do this:

{
  my $class = "determine class somehow";
  *maker = sub { return $class->new->add(@_) };
}

my $object = maker(@values);  # uses $class->new, baked in.

See... you *still* don't need to invoke the compiler at runtime.

Rainer> I really don't know why you think that running the Perl compiler from
Rainer> within Perl-code in order to create new compiled code should be
Rainer> avoided. I'll happily learn the reason for that, though.

Keep reading.  I'm not going to repeat things that have been said
repeatedly in the literature for at least a dozen years.

You do *not* need to use the compiler at runtime for anything where a
closure will work, and a closure is preferred.

print "Just another Perl hacker,"; # the original

-- 
Randal L. Schwartz - Stonehenge Consulting Services, Inc. - +1 503 777 0095
<merlyn@stonehenge.com> <URL:http://www.stonehenge.com/merlyn/>
Smalltalk/Perl/Unix consulting, Technical writing, Comedy, etc. etc.
See http://methodsandmessages.posterous.com/ for Smalltalk discussion


------------------------------

Date: Fri, 29 Jul 2011 19:44:30 +0100
From: Rainer Weikusat <rweikusat@mssgmbh.com>
Subject: Re: Generating an anonymous reference to an OO method
Message-Id: <87livh6i5t.fsf@sapphire.mobileactivedefense.com>

merlyn@stonehenge.com (Randal L. Schwartz) writes:
>>>>>> "Rainer" == Rainer Weikusat <rweikusat@mssgmbh.com> writes:
>
> Rainer> ... then you can effectively hardwire it by using eval to run the Perl
> Rainer> compiler to create suitable subroutine at runtime. 
>
> You can just as easily do this:
>
> {
>   my $class = "determine class somehow";
>   *maker = sub { return $class->new->add(@_) };
> }
>
> my $object = maker(@values);  # uses $class->new, baked in.
>
> See... you *still* don't need to invoke the compiler at runtime.

The whole point of this exercise is to avoid the runtime overhead of
keeping the $class scalar around and determining its value each time
the closure is invoked: Perl supports dynamic code generation, albeit
in a somewhat more contorted way than, say, Lisp, because Perl isn't
directly capable of modifying Perl-code at runtime, it can just
evaluate strings containing Perl-code. Consequently, in a situation
like the one above, it is possible to compile a dynamically created
subroutine which just performs the intended operation instead of using
a more general subroutine which could also perform other operations
but without this feature ever being used.

> Rainer> I really don't know why you think that running the Perl compiler from
> Rainer> within Perl-code in order to create new compiled code should be
> Rainer> avoided. I'll happily learn the reason for that, though.
>
> Keep reading.  I'm not going to repeat things that have been said
> repeatedly in the literature for at least a dozen years.
>
> You do *not* need to use the compiler at runtime for anything where a
> closure will work, and a closure is preferred.

Considering the output of this little program:

---------------
#!/usr/bin/perl

use Benchmark;
use Devel::Peek;

sub make_closure($)
{
    my $v = $_[0];
    return sub { return $v + 1; };
}

sub make_sub($)
{
    return eval "sub { return $_[0] + 1; }";
}

*cl = make_closure(3);
*su = make_sub(3);

print STDERR ("The closure\n");
DumpWithOP(\&cl);

print STDERR ("\nThe sub\n");
DumpWithOP(\&su);

print("\n");

timethese(-10, {
		cl => sub { cl(); },
		su => sub { su(); }});
---------------

the ordinary (but dynamically created) subroutine looks perferrable,
at least for anything which is kept around for a long time and/or much
more often executed than created. So, why should a closure be
preferred?

NB: "Stupid guy whose head will explode trying to follow MY superior
intellect" doesn't quite cut it since stupidity is pretty much a
precondition for arrogance.


------------------------------

Date: Fri, 29 Jul 2011 22:42:49 +0100
From: Rainer Weikusat <rweikusat@mssgmbh.com>
Subject: Re: Generating an anonymous reference to an OO method
Message-Id: <87r558ahly.fsf@sapphire.mobileactivedefense.com>

merlyn@stonehenge.com (Randal L. Schwartz) writes:
>>>>>> "Rainer" == Rainer Weikusat <rweikusat@mssgmbh.com> writes:

[...]

> Rainer> I really don't know why you think that running the Perl compiler from
> Rainer> within Perl-code in order to create new compiled code should be
> Rainer> avoided. I'll happily learn the reason for that, though.
>
> Keep reading.  I'm not going to repeat things that have been said
> repeatedly in the literature for at least a dozen years.

Out of curiosity, I've now also done a very cursory 'literature
search': The Camel-book, considering its usual 'no bullshit' approach
to technology', contains nothing applicable to this particular way of
using eval. Something which is easily available on the web,

          http://docstore.mik.ua/orelly/perl/advprog

has a quite enthusiastic chapter on eval,

	http://docstore.mik.ua/orelly/perl/advprog/ch05_01.htm

containing the following statement:

	For me, Perl's run-time evaluation capability is one of the
	biggest reasons for using the language. I use run-time
	evaluation for creating little snippets of code on the fly,
	which then execute at typical Perl speeds (i.e., fast!), for
	writing sophisticated interpreters for little languages.  The
	eval function is the gateway to this power.

Lastly, I also found this:

	No. Do not resort to eval-string if other means are
	available. You're firing up the compiler (slower than almost
	any other solution), and exposing yourself to hard to debug
	and hard to secure practices.
	http://www.perlmonks.org/?node_id=405165

While this statement is arguably true (Imagine that it even provides a
reason and not just a commandment!) it is also not really applicable
when using the compiler to compile some frequently executed piece of
code in order to reduce the time needed to execute it: Doing a very
unscientific experiment (meaning, "just ran it once"), the eval is
indeed about an order of magnitude slower than the closure-creation
but this will amortize itself (insofar total CPU time used is
concerned) if the completely compiled function is called more than
about 213 times. Also, there are of course situations where one
instance of 'doing something' with a relatively high latency in order
to have a lower latency when 'doing something' in future is a sensible
tradeoff.

I feel like closing this posting with a German paragraph because I'd
like to use an absolutely untranslatable 'Daniel Duesentrieb' quote
in it (that's Gyro Gearloose in English)

"In des tumben Toren Hand ist jedes Werkzeug Tand" ist sicher
zutreffend. Allerdings nicht der Umkehrschluss das jeder, der ein
Werkzeug in die Hand nimmt, wohl ein tumber Tor sein muesse ...


------------------------------

Date: Fri, 29 Jul 2011 12:40:35 -0400
From: "Uri Guttman" <uri@StemSystems.com>
Subject: Re: Search and replace question
Message-Id: <87ei19hwfw.fsf@quad.sysarch.com>

>>>>> "l" == laredotornado  <laredotornado@zipmail.com> writes:

  l> I'm using Perl 5.10.6 on Mac 10.6.6.  I want to execute a simple
  l> search and replace against a file ...

  l> my $searchAndReplaceCmd = "perl -pi -e 's/\\Q${localTestDir}\\E//g' $
  l> {testSuiteFile}";
  l> system( $searchAndReplaceCmd );

why are you calling out to a perl subprocess when you are already inside
perl? you can just read in the file, edit it and write it out again. the
-pi options aren't so useful when you just need to do that inside
perl. it is obviously causing you problems due to shell interpretation
and such. it also means your regex is more cluttered than it needed to
be.

  l> How do I do a search and replace when the variable in questions
  l> contains regular expression characters?  Thanks, - Dave

well, you can use perl to read/edit/write the file directly. you can use
File::Slurp to make that even easier. then again, you can use
File::Slurp's edit_file_lines sub to do it even more easily.

use File::Slurp qw( edit_file_lines ) ;

	edit_file_lines { s/$localTestDir//g } $test_file ;

and since you are doing the s/// globally, you can speed it up with
edit_file which slurps in the whole file into $_:

use File::Slurp qw( edit_file ) ;

	edit_file { s/$localTestDir//g } $test_file ;


done. no need to escape anything or worry about shell stuff or several
other issues you had with your code.

uri

-- 
Uri Guttman  --  uri AT perlhunter DOT com  ---  http://www.perlhunter.com --
------------  Perl Developer Recruiting and Placement Services  -------------
-----  Perl Code Review, Architecture, Development, Training, Support -------


------------------------------

Date: Fri, 29 Jul 2011 08:08:41 -0700
From: Keith Keller <kkeller-usenet@wombat.san-francisco.ca.us>
Subject: Re: XML::Simple drives me mad
Message-Id: <p0vag8xesq.ln2@goaway.wombat.san-francisco.ca.us>

On 2011-07-29, RedGrittyBrick <RedGrittyBrick@spamweary.invalid> wrote:
> On 29/07/2011 14:48, Denis Valdenaire wrote:
>> $VAR1 = [
>>            {
>>              'name' =>  'was6'
>>            },
>>            {
>>              'name' =>  'wasconf'
>>            }
>>          ];

You do realize that this is just Data::Dumper output, right?  It uses
$VAR1 as a dummy variable if you don't specify a variable name.

> my $VAR1 = [

Oh, I guess not.

To the OP, you need to operate on the $config object.  See if George's
code works for you.

--keith



-- 
kkeller-usenet@wombat.san-francisco.ca.us
(try just my userid to email me)
AOLSFAQ=http://www.therockgarden.ca/aolsfaq.txt
see X- headers for PGP signature information



------------------------------

Date: Fri, 29 Jul 2011 16:56:23 +0100
From: Henry Law <news@lawshouse.org>
Subject: Re: XML::Simple drives me mad
Message-Id: <ReqdnfVwPeC0Ra_TnZ2dnUVZ7omdnZ2d@giganews.com>

On 29/07/11 14:48, Denis Valdenaire wrote:
 ... snip
> $xml = '<configuration>
>          <sync_method type="common">
>              <sync_modules>
>                  <ena name="was6"/>
>                  <ena name="wasconf"/>
>                  <dis name="ihs"/>
>              </sync_modules>
> 	</sync_method></configuration>';
 ... etc
>
> $VAR1 = [
>            {
>              'name' =>  'was6'
>            },
>            {
>              'name' =>  'wasconf'
>            }
>          ];
>
> My question : what i am supposed to do if i want to parse each name ?
> like, processing was6 and then wasconf and then stop.

If you routinely want to process those <ena> elements by their names you 
might try directing XML::Simple to make the names the keys.  Does this 
help?  It depends on what else you're trying to do in the "real" program 
which you very properly pruned before posting it.

#!/usr/bin/perl
use strict; use warnings;   # Did you prune these too?
use XML::Simple;
use Data::Dumper;

my $xml = '<configuration>
         <sync_method type="common">
             <sync_modules>
                 <ena name="was6"/>
                 <ena name="wasconf"/>
                 <dis name="ihs"/>
             </sync_modules>
	</sync_method></configuration>';


my $config = XMLin($xml, KeyAttr => "name");

print Dumper($config->{sync_method}->{sync_modules}->{ena});
print "\nHere are the names\n",
    join(',', keys %{$config->{sync_method}->{sync_modules}->{ena}}),
    "\n";

$VAR1 = {
           'was6' => {},
           'wasconf' => {}
         };

Here are the names
was6,wasconf

-- 

Henry Law            Manchester, England


------------------------------

Date: Fri, 29 Jul 2011 17:01:59 +0100
From: RedGrittyBrick <RedGrittyBrick@spamweary.invalid>
Subject: Re: XML::Simple drives me mad
Message-Id: <4e32d978$0$2944$fa0fcedb@news.zen.co.uk>

On 29/07/2011 16:08, Keith Keller wrote:
> On 2011-07-29, RedGrittyBrick<RedGrittyBrick@spamweary.invalid>  wrote:
>> On 29/07/2011 14:48, Denis Valdenaire wrote:
>>> $VAR1 = [
>>>             {
>>>               'name' =>   'was6'
>>>             },
>>>             {
>>>               'name' =>   'wasconf'
>>>             }
>>>           ];
>
> You do realize that this is just Data::Dumper output, right?

Correct, I do.

> It uses
> $VAR1 as a dummy variable if you don't specify a variable name.
>

Not only that, but a feature of Data::Dumper is that can be used to 
serialize objects. You can use that output to reconstruct (deserialize) 
the object in such a way that future operations on the reconstituted 
object will behave exactly the same as they would with the original object.


>> my $VAR1 = [
>
> Oh, I guess not.

You guess wrong.

>
> To the OP, you need to operate on the $config object.  See if George's
> code works for you.

George's code is over-complex IMHO.

     my $result = $config->{sync_method}->{sync_modules}->{ena};
     for my $row (@$result) {
       print $row->{name}, "\n";
     }

Clearer?

-- 
RGB


------------------------------

Date: Fri, 29 Jul 2011 12:45:36 -0400
From: "Uri Guttman" <uri@StemSystems.com>
Subject: Re: XML::Simple drives me mad
Message-Id: <87aabxhw7j.fsf@quad.sysarch.com>

>>>>> "GM" == George Mpouras <nospam.gravitalsun@hotmail.com.nospam> writes:

  GM> foreach my $k1 (keys $config->{sync_method}->{sync_modules})
  GM> {
  GM> my $k2 = $config->{sync_method}->{sync_modules}->{$k1};

that is redundant. just loop over the values of that last hash and skip
the entire extra access line above. or do a each %hash in a while loop
and get the key and the value. just access the desired level which is an
array ref and loop over that. no need to do the deep access twice.


  GM>  if ( 'ARRAY' eq ref $k2 )
  GM>  {
  GM>   foreach (@{$k2})
  GM>   {
  GM>   print "$k1 , $_->{'name'}\n";
  GM>   }
  GM>  }
  GM>  elsif ( 'HASH' eq ref $k2 )
  GM>  {
  GM>   foreach my $k3 (keys %{$k2})
  GM>   {
  GM>   print "$k3 $k2->{$k3}\n";
  GM>   }
  GM>  }
  GM> } 

and XML::Simple can force single elements to be parsed into arrays so
you can always process an array of items which simplifies your code.

uri

-- 
Uri Guttman  --  uri AT perlhunter DOT com  ---  http://www.perlhunter.com --
------------  Perl Developer Recruiting and Placement Services  -------------
-----  Perl Code Review, Architecture, Development, Training, Support -------


------------------------------

Date: Fri, 29 Jul 2011 11:21:39 -0700 (PDT)
From: "C.DeRykus" <derykus@gmail.com>
Subject: Re: XML::Simple drives me mad
Message-Id: <2ab9a910-9da2-495b-bcdc-571079fa63ea@r11g2000prd.googlegroups.com>

On Jul 29, 6:48=A0am, Denis Valdenaire <dvaldena...@gmail.com> wrote:
> Hello,
>
> Here is my problem. I have a "data" in perl (I said a "data", because
> i don't know WHAT it is. I know what it is not : not an ARRAY ref, not
> an ARRAY, not a HASH ref, etc. etc. Every attempt i made to parse it
> fails with an error message of that kind.), that was provider by
> XML::Simple::XMLIn();
>
> Let's consider the code :
>
> #!/usr/bin/perl
>
> use XML::Simple;
> use Data::Dumper;
>
> $xml =3D '<configuration>
> =A0 =A0 =A0 =A0 <sync_method type=3D"common">
> =A0 =A0 =A0 =A0 =A0 =A0 <sync_modules>
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 <ena name=3D"was6"/>
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 <ena name=3D"wasconf"/>
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 <dis name=3D"ihs"/>
> =A0 =A0 =A0 =A0 =A0 =A0 </sync_modules>
> =A0 =A0 =A0 =A0 </sync_method></configuration>';
>
> my $config =3D XMLin($xml, KeyAttr =3D> "");
>
> print Dumper($config->{sync_method}->{sync_modules}->{ena});
>
> That gives me the following output (THE VERY "data") :
>
> $VAR1 =3D [
> =A0 =A0 =A0 =A0 =A0 {
> =A0 =A0 =A0 =A0 =A0 =A0 'name' =3D> 'was6'
> =A0 =A0 =A0 =A0 =A0 },
> =A0 =A0 =A0 =A0 =A0 {
> =A0 =A0 =A0 =A0 =A0 =A0 'name' =3D> 'wasconf'
> =A0 =A0 =A0 =A0 =A0 }
> =A0 =A0 =A0 =A0 ];
>
> My question : what i am supposed to do if i want to parse each name ?
> like, processing was6 and then wasconf and then stop.
>
> I believe I tried everything (keys, foreach, each, #{@->{%}}, etc...).
> Do I do it the wrong way ?
>


That's the right idea... just need to drill down
to bedrock. Here's a possible solution:

   my $array_ref =3D $config->{sync_method}
                     ->{sync_modules}->{ena};

   foreach my $array_elem ( @{$array_ref} )
   {
     while ( my($key,$value) =3D each %{$array_elem} )
     {
        print "$key=3D$value\n";
     }
   }

perldoc perldsc for more info and examples..

--
Charles DeRykus


------------------------------

Date: Fri, 29 Jul 2011 11:27:09 -0700
From: Keith Keller <kkeller-usenet@wombat.san-francisco.ca.us>
Subject: Re: XML::Simple drives me mad
Message-Id: <tkabg8x46t.ln2@goaway.wombat.san-francisco.ca.us>

On 2011-07-29, RedGrittyBrick <RedGrittyBrick@spamweary.invalid> wrote:
>
> Not only that, but a feature of Data::Dumper is that can be used to 
> serialize objects. You can use that output to reconstruct (deserialize) 
> the object in such a way that future operations on the reconstituted 
> object will behave exactly the same as they would with the original object.

Yes, it can, but your code doesn't actually help the OP, who isn't using
that feature.

--keith

> George's code is over-complex IMHO.
>
>      my $result = $config->{sync_method}->{sync_modules}->{ena};
>      for my $row (@$result) {
>        print $row->{name}, "\n";
>      }
>
> Clearer?

Not ''clearer'', but certainly more useful to the OP.

--keith

-- 
kkeller-usenet@wombat.san-francisco.ca.us
(try just my userid to email me)
AOLSFAQ=http://www.therockgarden.ca/aolsfaq.txt
see X- headers for PGP signature information



------------------------------

Date: Fri, 29 Jul 2011 12:09:49 -0700 (PDT)
From: Klaus <klaus03@gmail.com>
Subject: Re: XML::Simple drives me mad
Message-Id: <d7bbbe92-6f2a-43d1-b08b-59d119f6c1c8@k27g2000yqn.googlegroups.com>

On 29 juil, 15:48, Denis Valdenaire <dvaldena...@gmail.com> wrote:
> Hello,
>
> Here is my problem. I have a "data" in perl (I said a "data", because
> i don't know WHAT it is. I know what it is not : not an ARRAY ref, not
> an ARRAY, not a HASH ref, etc. etc. Every attempt i made to parse it
> fails with an error message of that kind.), that was provider by
> XML::Simple::XMLIn();
>
> Let's consider the code :
>
> #!/usr/bin/perl
>
> use XML::Simple;
> use Data::Dumper;
>
> $xml =3D '<configuration>
> =A0 =A0 =A0 =A0 <sync_method type=3D"common">
> =A0 =A0 =A0 =A0 =A0 =A0 <sync_modules>
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 <ena name=3D"was6"/>
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 <ena name=3D"wasconf"/>
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 <dis name=3D"ihs"/>
> =A0 =A0 =A0 =A0 =A0 =A0 </sync_modules>
> =A0 =A0 =A0 =A0 </sync_method></configuration>';
>
> my $config =3D XMLin($xml, KeyAttr =3D> "");
>
> print Dumper($config->{sync_method}->{sync_modules}->{ena});
>
> That gives me the following output (THE VERY "data") :
>
> $VAR1 =3D [
> =A0 =A0 =A0 =A0 =A0 {
> =A0 =A0 =A0 =A0 =A0 =A0 'name' =3D> 'was6'
> =A0 =A0 =A0 =A0 =A0 },
> =A0 =A0 =A0 =A0 =A0 {
> =A0 =A0 =A0 =A0 =A0 =A0 'name' =3D> 'wasconf'
> =A0 =A0 =A0 =A0 =A0 }
> =A0 =A0 =A0 =A0 ];
>
> My question : what i am supposed to do if i want to parse each name ?
> like, processing was6 and then wasconf and then stop.
>
> I believe I tried everything (keys, foreach, each, #{@->{%}}, etc...).
> Do I do it the wrong way ?

It's actually an array-ref, therefore you use @{...}

for (@{$config->{sync_method}->{sync_modules}->{ena}}) {
    print "Do something with >$_->{name}<\n";
}

*********************************************
alternatively, you can use XML::Reader:

use XML::Reader;

my $rdr =3D XML::Reader->new(\$xml, {mode =3D> 'branches'},
  { root =3D> '/configuration/sync_method/sync_modules/ena',
    branch =3D> ['/@name'] },
);

while ($rdr->iterate) {
    print "Do something with >", $rdr->value, "<\n";
}


------------------------------

Date: 6 Apr 2001 21:33:47 GMT (Last modified)
From: Perl-Users-Request@ruby.oce.orst.edu (Perl-Users-Digest Admin) 
Subject: Digest Administrivia (Last modified: 6 Apr 01)
Message-Id: <null>


Administrivia:

To submit articles to comp.lang.perl.announce, send your article to
clpa@perl.com.

Back issues are available via anonymous ftp from
ftp://cil-www.oce.orst.edu/pub/perl/old-digests. 

#For other requests pertaining to the digest, send mail to
#perl-users-request@ruby.oce.orst.edu. Do not waste your time or mine
#sending perl questions to the -request address, I don't have time to
#answer them even if I did know the answer.


------------------------------
End of Perl-Users Digest V11 Issue 3459
***************************************


home help back first fref pref prev next nref lref last post