Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

how to assign hash element value to scalar?

by jugdish114 (Initiate)
on Nov 14, 2006 at 19:02 UTC ( [id://584029]=perlquestion: print w/replies, xml ) Need Help??

jugdish114 has asked for the wisdom of the Perl Monks concerning the following question:

sorry, here's a dumb simple question:

I am using the XML::Simple module to parse XML into a structure. This code works fine:

print "resultid:" . $response->{channel}->{result}->{resultid};

but assigning the value of the element has been difficult for me:

my $resultid = $response->{channel}->{result}->{resultid};

this does not work. I want to save the value of the has element as a scalar, or string, or whatever, for future use.

getting back into perl after a long absence. thanks in advance fer yer help.

fc thanks, here's some code examples for your reference:
#all this works: my $xmlsimple = XML::Simple->new(); my $response = $xmlsiple->XMLin($xml_content->content); print "resultid:" . $response->{channel}->{result}->{resultid}; #this doesn't work: my $resultid = $response->{channel}->{result}->{resultid}; print "resultid: " . $resultid;

the output looks like this:

resultid:

but should look like this:

resultid: The item was added to the database.

thanks again!
fc
OK, here is much more code for your review, thanks:
use XML::Simple; use LWP::Simple; use Data::Dumper; use HTTP::Request::Common; use LWP::UserAgent; my $url = "http://localhost/xml/add_order.xml"; my $UserAgent = LWP::UserAgent->new(agent => 'perl post'); my $xml_content = $UserAgent->request(POST $url,["userid" => $userid +, "password" => $pass +word, "projectid" => $pro +jectid, "ordertypeid" => $o +rdertypeid, "orderdateid" => $o +rderdateid, "accountid" => $acc +ountid, "segcodeid" => $seg +codeid, "marketid" => $mark +etid, "marketday" => $mar +ketday, "marketmonth" => $m +arketmonth, "marketyear" => $ma +rketyear, "putcall" => $putca +ll, "strikeprice" => $s +trikeprice, "bs" => $bs, "quantity" => $quan +tity, "orderprice" => $or +derprice, "entered_by" => $en +tered_by ]); print $xml_content->error_as_HTML unless $xml_content->is_success; #if we want to see the XML #printf $xml_content->content; # also see ->code, ->is_info, ->is_success, ->is_error, - +>header, ->message, etc my $xmlsimple = XML::Simple->new( ); my $response = $xmlsimple->XMLin($xml_content->content); #if we wanted to see the object as a structure: #printf Dumper($response); if ($response->{channel}->{error}->{errorid} == "") { print "resultid: " . $response->{channel}->{result}->{resultid} . +"\n"; print "resultdesc: " . $response->{channel}->{result}->{resultdesc +} . "\n"; print "orderid: " . $response->{channel}->{result}->{orderid} . "\ +n"; my $resultid = $response->{channel}->{result}->{resultid}; +#ERROR my $resultdesc = ${\$response->{channel}->{result}->{resultdesc}}; + #ERROR my $orderid = $response->{channel}->{result}->{orderid}; +#ERROR printf "ERROR resultid:" . $resultid . "\n"; printf "ERROR: resultdesc:" . \$resultdesc . "\n"; printf "ERROR: orderid:" . $orderid . "\n\n"; # foreach my $tmp (@{$response->{channel}->{result}}) { # print "resultid: " . $tmp->{resultid} . "\n"; # print "resultdesc: " . $tmp->{resultdesc} . "\n"; # print "orderid: " . $tmp->{orderid} . "\n"; # print "\n"; # } } else { print "errorid: " . $response->{channel}->{error}->{errorid} . "\n +"; print "error desc: " . $response->{channel}->{error}->{errordesc} +. "\n"; print "\n"; }; my @ret_arry = ("test", $resultid, $resultdesc, $orderid); printf "ret_arry0:" . $ret_arry[0] . "\n"; printf "ret_arry1:" . $ret_arry[1] . "\n"; printf "ERROR ret_arry2:" . $ret_arry[2] . "\n"; printf "ERROR ret_arry3:" . $ret_arry[3] . "\n\n"; #%ret_hash = (resultid => "a", # resultdesc => "b"); return @ret_arry;
Grandfather, et al:

Here's a link with a static XML file that is created for my code:
http://frank.mazzy.com/xfer/tmp.xml
And here is output from the command line:
Adding order resultid: 0 resultdesc: Success - Order 109 has been added to ProjectID 4217. orderid: 109 ERROR resultid:0 ERROR: resultdesc:SCALAR(0x181187c) ERROR: orderid:109 ret_arry0:test ret_arry1: ERROR ret_arry2: ERROR ret_arry3: array: test arry0: test arry1: ERROR arry2: ERROR arry3: done
thanks again!

Edited by planetscape - added code tags

Replies are listed 'Best First'.
Re: how to assign hash element value to scalar?
by liverpole (Monsignor) on Nov 14, 2006 at 19:35 UTC
    Hi jugdish114,

    Can you post your exact code sample, please?

    In the snippet you posted:

    #all this works: my $xmlsimple = XML::Simple->new(); my $response = $xmlsiple->XMLin($xml_content->content); print "resultid:" . $response->{channel}->{result}->{resultid};

    there's clearly a typo; in one place you have $xmlsimple, and another $xmlsiple.  I'm guessing maybe the part that "doesn't work" might be the reverse -- a typo which you've inadvertently corrected when you posted.

    Try actually cutting and pasting your code (and be sure to use "code tags" (eg. <code> and </code>) around any code examples you submit).

    One other suggestion -- put use strict; and use warnings; at the beginning of your program.  That may even solve your problem right away!


    s''(q.S:$/9=(T1';s;(..)(..);$..=substr+crypt($1,$2),2,3;eg;print$..$/
      yes, those were simple errors when i was typing the code into the webform. the code runs, and does not use '$xmlsiple' anywhere.

      so...

      any ideas why i can't move the value of this hash element into a simple scalar? i'm guessing i have to do somehting like cast the hash as an array or string or something.

      thanks.
Re: how to assign hash element value to scalar?
by liverpole (Monsignor) on Nov 14, 2006 at 20:07 UTC
    I can see a couple more issues.

    One is that, when (as I mentioned) you use strict; and use warnings;, you get:

    Global symbol "$userid" requires explicit package name at x line 17. Global symbol "$password" requires explicit package name at x line 18. Global symbol "$projectid" requires explicit package name at x line 19 +. Global symbol "$ordertypeid" requires explicit package name at x line +20. Global symbol "$orderdateid" requires explicit package name at x line +21. Global symbol "$accountid" requires explicit package name at x line 22 +. Global symbol "$segcodeid" requires explicit package name at x line 23 +. Global symbol "$marketid" requires explicit package name at x line 24. Global symbol "$marketday" requires explicit package name at x line 25 +. Global symbol "$marketmonth" requires explicit package name at x line +26. Global symbol "$marketyear" requires explicit package name at x line 2 +7. Global symbol "$putcall" requires explicit package name at x line 28. Global symbol "$strikeprice" requires explicit package name at x line +29. Global symbol "$bs" requires explicit package name at x line 30. Global symbol "$quantity" requires explicit package name at x line 31. Global symbol "$orderprice" requires explicit package name at x line 3 +2. Global symbol "$entered_by" requires explicit package name at x line 3 +4. Global symbol "$resultid" requires explicit package name at x line 80. Global symbol "$resultdesc" requires explicit package name at x line 8 +1. Global symbol "$orderid" requires explicit package name at x line 82.

    Of these, note that $resultid is defined within the if clause:

    if ($response->{channel}->{error}->{errorid} == "") { # ... my $resultid = $response->{channel}->{result}->{resultid};\ # ... };

    ... so of *course* it's not going to be available outside of the block.

    You're also trying to return from outside of a subroutine, as well as comparing a string using "==" in the if statement I referenced above (you should really either use eq for string comparisons, or change "" to the numeric 0).

    Is this the whole code sample, or just part of it?

    And what happens when [id://jugdish114|you] add use strict; and use warnings; to it?


    s''(q.S:$/9=(T1';s;(..)(..);$..=substr+crypt($1,$2),2,3;eg;print$..$/
      thanks, yes this is part of a subroutine, here's the beginning of it:
      sub enter_order { my ($userid) = $_[0]; my ($password) = $_[1]; my ($projectid) = $_[2]; my ($ordertypeid) = $_[3]; my ($orderdateid) = $_[4]; my ($accountid) = $_[5]; my ($segcodeid) = $_[6]; my ($marketid) = $_[7]; my ($marketday) = $_[8]; my ($marketmonth) = $_[9]; my ($marketyear) = $_[10]; my ($putcall) = $_[11]; my ($strikeprice) = $_[12]; my ($bs) = $_[13]; my ($quantity) = $_[14]; my ($orderprice) = $_[15]; my ($entered_by) = $_[16];

      yes, when i add 'use strict' it is not very pretty, some of the code outside the subroutine give errors.

      and thanks for pointing out the error with the "==" rather than "eq" i think i write in too many languages to keep them straight.

      see ya,
            when i add 'use strict' it is not very pretty, some of the code outside the subroutine give errors.

        You don't really believe that by not adding 'use strict' it means the errors magically go away, do you? :-)


        s''(q.S:$/9=(T1';s;(..)(..);$..=substr+crypt($1,$2),2,3;eg;print$..$/
        Well, as an aside ... if you pass that many parameters to a subroutine, have you considered using a hash and using name => value pairs? That would greatly reduce the risk of errors and makes all these variable declarations unnecessary ...

        I was thinking of something like the following ... suitably adjusted to your concrete requirements of course (are all parameters necessary, should they get a default value if not given, ...)

        # call the sub my_sub(userid => 'foo', password => 'bar'); sub my_sub { my %default_values = (userid => 'user', password => 'passwd'); my %param = (%default_values, @_); print $param{userid}, $/; print $param{password}, $/; # ... } # or with all required arguments sub my_sub { my @required = qw/userid password/; my %param = @_; for my $req (@required) { die "Subroutine my_sub called without required parameter: $req" unless exists $param{$req}; } print $param{userid}, $/; print $param{password}, $/; # ... }

        -- Hofmator

        Code written by Hofmator and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.

        It may be that you want to explicitly show which element of the subroutine's arguments is assigned to which variable but if not, you could save some typing by doing

        my ($userid, $password, $projectid, ... , $entered_by) = @_;

        I hope this is of use.

        Cheers,

        JohnGG

Re: how to assign hash element value to scalar?
by GrandFather (Saint) on Nov 14, 2006 at 19:42 UTC

    The update is good, but doesn't help :). Can you post the two variants along with just enough data to populate $xml_content->content and show the problem? Hint: use a __DATA__ section to provide the $xml_content->content content, or simple replace $xml_content->content with $str initialised to your sample XML (using a heredoc perhaps?).

    By the way,

    $response->{channel}->{result}->{resultid}

    can be written

    $response->{channel}{result}{resultid}

    and you can interpolate directly into the string rather than using concatenation by

    print "resultid: $resultid";

    DWIM is Perl's answer to Gödel
Re: how to assign hash element value to scalar?
by j3 (Friar) on Nov 14, 2006 at 19:15 UTC
    Can you please provide us with a small sample of code that doesn't behave as you'd expect?

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://584029]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (4)
As of 2024-04-26 05:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found