develooper Front page | perl.beginners | Postings from July 2007

Re: parsing a line

Thread Previous | Thread Next
From:
alok nath
Date:
July 1, 2007 10:37
Subject:
Re: parsing a line
Message ID:
510316.7828.qm@web53202.mail.re2.yahoo.com
Hi Chas,
  Can you please explain the portion ( ([\w ]*\w)\s*= )of the regex.?
  And why its stored in $s.Can it be directly stored in hash my %rec.
Thanks
Alok
          

if (my %rec = $s =~ /\s*([\w ]*\w)\s*=\s*"(.*?)"/g) {
        my $id   = exists $rec{ID} ? $rec{ID} : "not set";
        my $dir  = exists $rec{DirAbsolute} ? $rec{DirAbsolute} : "not set";
        my $desc = exists $rec{'Test Description'} ? $rec{'Test
Description'} : "not set";
        print "id $id dir $dir desc $desc\n";
}


----- Original Message ----
From: Chas Owens <chas.owens@gmail.com>
To: alok nath <aloknathlight@yahoo.com>
Cc: beginners@perl.org
Sent: Thursday, June 28, 2007 7:45:53 PM
Subject: Re: parsing a line


On 6/28/07, alok nath <aloknathlight@yahoo.com> wrote:
snip
> if( $_ =~ m/ID\s=\s"(.*?)"\sDirAbsolute/){
snip

It does look fragile.  A lot depends on how likely the real input
matches the example you gave.  That regex will break if the input is

<Test Description = "Test 1" ID =  "ID A1" DirAbsolute = "C:/perl"/>

Note the second space after the "ID =".  Also, you can generalize the
code by using character classes:

if (my %rec = $s =~ /\s*([\w ]*\w)\s*=\s*"(.*?)"/g) {
        my $id   = exists $rec{ID} ? $rec{ID} : "not set";
        my $dir  = exists $rec{DirAbsolute} ? $rec{DirAbsolute} : "not set";
        my $desc = exists $rec{'Test Description'} ? $rec{'Test
Description'} : "not set";
        print "id $id dir $dir desc $desc\n";
}

-- 
To unsubscribe, e-mail: beginners-unsubscribe@perl.org
For additional commands, e-mail: beginners-help@perl.org
http://learn.perl.org/


 
____________________________________________________________________________________
Don't get soaked.  Take a quick peak at the forecast
with the Yahoo! Search weather shortcut.
http://tools.search.yahoo.com/shortcuts/#loc_weather
Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About