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

I have the need to pull out values in a XML file. Below is an example of the script I have:

#!/usr/bin/perl -w use strict; use warnings; my $mystring = "ABC<ID>blahblah</ID>DEF"; if ( $mystring =~ /<ID>($.)<\/ID>/) { my $ID = $1; print "$ID\n"; }

When I run it, I get:

dpich@m6400-vb:~/Documents$ perl ./xml.pl Use of uninitialized value $. in regexp compilation at ./xml.pl line 6 +. dpich@m6400-vb:~/Documents$

I'm confussed. Why am I getting an unititialzed value error? Isn't '$.' representing text between the <ID> and </ID> tags? My desired result is to place 'blahblah' in the variable $ID.

Replies are listed 'Best First'.
Re: regex/perl question about uninitialized value
by JavaFan (Canon) on Nov 03, 2011 at 14:16 UTC
    $. is a read-only variable, returning the line number of the last read line. It's undefined because you haven't read any.

    Perhaps you are confusing .* and $.?

      $. is a read-only variable

      $. is definitely NOT read-only.

Re: regex/perl question about uninitialized value
by toolic (Bishop) on Nov 03, 2011 at 14:23 UTC
    Isn't '$.' representing text between the <ID> and </ID> tags?
    No. Refer to:
    perldoc -v '$.'

    Also, consider using an XML parser from CPAN, such as XML::Twig, instead of a regex.

Re: regex/perl question about uninitialized value
by pvaldes (Chaplain) on Nov 03, 2011 at 14:46 UTC
    #!/usr/bin/perl -w use strict; my $mystring = 'ABC<ID>blahblah</ID>DEF'; if ( $mystring =~ /<ID>(.*?)<\/ID>/) { my $ID = $1; print "$ID\n"; }
      thank you pvaldes. That worked great!!

      This is an interesting hipothetic situation:

      #!/usr/bin/perl -w use strict; open <ID>, '<', 'textfile.txt'; # a lot of lines later... my $mystring = "ABC<ID>blahblah</ID>DEF"; if ( $mystring =~ /<ID>(.*?)<\/ID>/) { my $ID = $1; print "$ID\n"; # OOOPS.... }

      The moral of the history is... always check the ""

        I've no idea what problem you're describing here. Well, except that
        open <ID>, '<', 'textfile.txt';
        looks very strange. But that doesn't seem related to the line with the OOOPS.