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

I am trying to fetch the number that appears where the number 148 is. Sometimes the number changes and I always want to fetch whatever number is located where 148 is.
('AA', 'B','2','ProjectId','148')"> Unique Information Here (Index)
Here is my LONG attempt at it?? if ( $line =~ /\'AA\'\,\'B\'\,\'2\'\,\'ProjectId\'\,\'(\d{3})\'\)\">Unique Information Here (Index)/ )

Replies are listed 'Best First'.
Re: Fetching a number
by cbro (Pilgrim) on Jun 02, 2003 at 19:19 UTC
    If your lines are always going to be 5 fields long...seperated by commas:
    my ($s1, $s2, $s3, $pname, $index) = split(/,/, $line);
    Update:
    Or if the line looks exactly like
    ('AA', 'B','2','ProjectId','148')"> Unique Information Here (Index)
    my ($before, $after) = split(/>/, $line); my ($s1,$s2,$s3,$pname,$index) = split (/,/, $before); and then just trim off the ',), and " characters from $index.
Re: Fetching a number
by halley (Prior) on Jun 02, 2003 at 19:20 UTC

    One, it works. What's your question? "Will it work" or "How to do it better?"

    Two, here's some ideas on the latter. Don't hardwire anything else about the string which may have different values. Don't escape junk that needs no escaping. Don't fix the length if you might need longer or shorter matches.

    print $1,$/ if $line =~ m/ ' (\d+) ' \) /x;

    --
    [ e d @ h a l l e y . c c ]

Re: Fetching a number
by Limbic~Region (Chancellor) on Jun 02, 2003 at 22:12 UTC
    Anonymous Monk,
    From what you have shown - it is a fixed string up to the number you are looking for. This screams "use substr". Your example showed \d{3} which implies it will always be a 3 digit number, but since you didn't say that - I offer the following two solutions - neither using a regex.
    #!/usr/bin/perl -w use strict; my $string = qq{('AA','B','2','ProjectId','148')">Unique Information H +ere (Index)}; my $number = substr($string,27,3); #my $number = substr($string,27,index($string,"'",27) - 27); print "$number\n";
    Just switch the comments for my $number depending on if it will always be a 3 digit number or not.

    Cheers - L~R