#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    1
    Rep Power
    0

    Question Iterating through an xml::simple array using a variable?


    Hello,

    I am new to Perl and trying to write a Perl program to read in an XML file and generate C code (a pointer array of 246 variables) based on the XML file contents. I was having trouble using a numeric variable for a 'for' loop in the array for XML::Simple and wondering if someone can provide insight on what I am doing wrong. The code looks like this,

    use XML::Simple;

    use Data:umper;


    $xml = new XML::Simple (KeyAttr=>[]);


    #read XML files

    $conf_data = $xml->XMLin("tempConfigDataFile.xml");



    open CFILE, ">ACM_FM.c";

    print_global_defs();


    sub print_global_defs

    {

    my @FC_Names = @{ $conf_data->{'SW-SYSTEMS'}->{'SW-SYSTEM'}->{'CONF-SPEC'}->{'CONF-ITEMS'}->{'CONF-ITEM'} };

    my $FC_Count = @FC_Names;


    for(my $i = 0; $i < $FC_Count; $i++) {

    print CFILE "&", @FC_Names['$i']->{'CONF-ITEMS'}->{'CONF-ITEM'}->{'CONF-ITEMS'}->{'CONF-ITEM'}->[0]->{VT}, "}\n";

    }

    }


    The problem is that inside the 'for' loop, the variable $i in @FC_Names['$i] always gets evaluated to 0 and it always returns the same element (first one) from the XML file. Thus the c file gets printed out with the same element (the first one) repetatively instead of all the elements consecutively.

    Can anyone tell me how to correctly reference the numeric variable 'i' inside the array FC_Names so that the correct value of i is used as an index insde the array such that the correct element of the XML file is referenced?

    I would appreciate any help.

    Thanks!
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Jun 2012
    Posts
    776
    Rep Power
    495
    Remove the quote marks around $i in your subscript of the array.
  4. #3
  5. kill 9, $$;
    Devshed Supreme Being (6500+ posts)

    Join Date
    Sep 2001
    Location
    Shanghai, An tSín
    Posts
    6,897
    Rep Power
    3886
    To expand on the above answer: using single quotes means that your variable isn't interpolated (i.e. it's not replaced with its value). Instead, you're literally using the string '$i' as an array index. That will evaluate to 0 if used as a numeric value.

    This is a good example of why you should always use warnings in your programs. If you had, you'd have seen something like this:
    Code:
    Argument "$i" isn't numeric in array element at test.pl line 18.

    Comments on this post

    • Axweildr agrees

IMN logo majestic logo threadwatch logo seochat tools logo