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

HI...
I been trying to do this for a while now....
Suppose i have a text file.. say data.txt that contains the following information:
name = "varun" ip='9.12.23.222' #including the irregular spaces
i'm not quiet sure how to use data::dumper...
but is it possible to read the ip address and name into separate variables in my perl code.
something like data->name, the way we reference other data
If so then how?
Oh and yea does it make a difference in accessing the data from this text file if i use single quotes and double quotes?
Here's the code im currently using:
#!/usr/bin/perl use strict; use warnings; $data="./DATA.txt"; if (open(INFILE, $data)) { @svr_raw = <INFILE>; close(INFILE); } else { print "File $data does not exist or is corrupted\n"; } print $svr_raw->{name};
OUTPUT :
administrator@varunraj ~/scripts $ ./learn_2.pl Global symbol "$data" requires explicit package name at ./learn_2.pl l +ine 6. Global symbol "$data" requires explicit package name at ./learn_2.pl l +ine 8. Global symbol "@svr_raw" requires explicit package name at ./learn_2.p +l line 9. Global symbol "$data" requires explicit package name at ./learn_2.pl l +ine 12. Global symbol "$svr_raw" requires explicit package name at ./learn_2.p +l line 15 Execution of ./learn_2.pl aborted due to compilation errors.
Required output:
varun

Replies are listed 'Best First'.
Re: Accessing data present in a text file with references...
by CountZero (Bishop) on Feb 14, 2010 at 20:46 UTC
    Data::Dumper has nothing to do with your problem.

    Have a look at the following:

    use strict; use warnings; my %data; while (<DATA>) { my ($key, $value) = split /\s*=\s*/; if (m/["']([^'"]+)/) { $data{$key} = $1; } } for my $key (keys %data) { print "$key = $data{$key}\n"; } __DATA__ name = "varun" ip='9.12.23.222' #including the irregular spaces
    The data are stored in a hash with as keys the word(s) before the = sign and value everything between the single or double quotes to the right of the equal-sign.

    If you really want to access your data as $data->name rather than as $data{'name'} then have a look at perlboot. Note that in this case the arrow operator -> is not used to dereference references here but as a method invocator.

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

      cool... thanks man....
      could u explain this part a bit....
      my ($key, $value) = split /\s*=\s*/; if (m/["']([^'"]+)/) {
      thanks for this and the link man
      ++ when does one use data::dumper?
        The while loop puts each line in $_ which is some sort of universal default variable.

        The split splits the string in $_ on the following pattern: "zero or more spaces; equal sign; zero or more spaces" and puts the results of this splitting in the variables $key and $value (actually $value is not used in my script, but I left it in otherwise you might wonder where the second part of the split went to).

        m/["']([^'"]+)/ is a regular expression match and it (also) does some pattern matching, again on the contents of the $_ variable. It tries to match the following pattern: "one single or one double quote; one or more times anything but a single or double quote". The "one or more times anything but a single or double quote" pattern is captured (see the parentheses round the [^'"]?) into the $1 variable. If the match succeeds, we store the contents of $1 into the %data hash keyed by $key.

        CountZero

        A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

Re: Accessing data present in a text file with references...
by GrandFather (Saint) on Feb 14, 2010 at 21:07 UTC

    Please don't update your node without indicating that you have done so! The code and output is appreciated, but wasn't part of the original node.

    Consider the following:

    #!/usr/bin/perl use strict; use warnings; use Data::Dump; my $filename = "./DATA.txt"; open my $outFile, '>', $filename or die "Can't create $filename: $!"; print $outFile <<'FILE_DATA'; name = "varun" ip='9.12.23.222' #including the irregular spaces FILE_DATA close $outFile; open my $inFile, '<', $filename or die "Can't open $filename: $!"; my %data; while (<$inFile>) { chomp; my ($id, $value) = split /\s*=\s*/; $data{$id} = $value; } print Data::Dump::dump (\%data);

    Prints:

    { ip => "'9.12.23.222' #including the irregular spaces", name => "\"varun\"", }

    which creates a temporary file as part of the sample code (so the while thing is self contained), reads the file and builds a hash containing name/value pairs (this may not do it for you if there are multiple lines in your file using the same name), then dumps the resulting data structure as you might do when you haven't figured out how to use the debugger and want to see what you got.


    True laziness is hard work
Re: Accessing data present in a text file with references...
by GrandFather (Saint) on Feb 14, 2010 at 20:31 UTC

    Show us what you have tried. You seem to have a large number of misunderstandings related to this, but without your code it may not be easy to clear them up.

    Remember to use strictures (use strict; use warnings;), show us runable code, show us some sample input (what you have is great) and show us the the results you expect and the results you get.


    True laziness is hard work
      I tried using a reference to the file handle as in i read the file as an array..
      i was not sure how the link up thing works or how the mapping is supposed to be done...
      I have just been fiddling around with this as in trying to read meaningful data from a text file.
Re: Accessing data present in a text file with references...
by biohisham (Priest) on Feb 15, 2010 at 08:54 UTC
    when you turn the strictures on, they give you warnings as long as you don't declare your variables with the "my" keyword, this serves to localize the variables to the current scope. "my" use can be wide-spread but there are other keywords out there ours and local. You can readily find out many discussions involving the conditions each one of these is used under.

    So you could have declared the variables "$data", "@svr_raw" by preceding them with the "my" keyword, that would've given you hints that @svr_raw has been declared as an array but then you used a hash ref.

    The module Data::Dumper is used to stringify data structures, (i.e it represents the strings that a data structure - when appropriately referenced- would show), hence you can look at the dumped structure and make judgments on how it can best be accessed. I would stress that it is very handy to learn advanced data structures in Perl,

    Are some of the resources for you...

    "Oh and yea does it make a difference in accessing the data from this text file if i use single quotes and double quotes? "
    double quotes and single quotes contexts come into light if you are accessing variables, since interpolation is affected by the way a variable is enclosed, double quotes allow variable interpolation and single quotes do not..
    $name = "varun monk"; print "$name\n"; print '$name\n';

    Run this code, which does work similar to what you intend
    use strict; use warnings; my $data={}; #declare an anonymous hash while(<DATA>){ chomp; my ($key, $val)=split /\s*=\s*/; $data->{$key}=$val; } print "name=>", $data->{name},"\n"; print "ip=>", $data->{ip},"\n"; ##View the data structure## use Data::Dumper; print Dumper($data); __DATA__ name = "varun" ip = "9.12.23.222";

    Excellence is an Endeavor of Persistence. Chance Favors a Prepared Mind.