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

I am trying to match a variable in a fixed width file with regex, I would like to return the matched record into an array for further processing. here is what I am trying (it returns nothing)
sub get_domkey{ + while(<>){ + if (/\*([^*]+)\*/) { + $key=$1; + print "$key\n"; + &get_domcf; + } + } + } + sub get_domcf{ + open DOM_CF, '/u/ds2/r61/domcf.dat' or die "Can't open DOM control fil +e because $!\n"; + while (<DOM_CF>){ + if (/\$key/){ + @dom_opts=$1; + } + } + }
The sub get_domkey is grabbing the key and printing, when I try to use it to grab the record in sub get_domcf it returns nothing, I have tried several different regexs but have had no luck in getting any to pass the record to @dom_opts, any help would be greatly appreciated :) -Aseidas

Replies are listed 'Best First'.
Re: Matching a variable in a fixed width file
by jsprat (Curate) on May 08, 2002 at 23:06 UTC
    It looks like you have metacharacters in $key (*, right?) that you want interpreted literally. You cannot escape the entire scalar with a single \, you are only escaping the dollar sign -/\$key/ will match the string '$key'.

    If you quote $key with /\Q$key\E/, that should give you what you want.

    For more info, try perldoc perlre.

Re: Matching a variable in a fixed width file
by ozone (Friar) on May 08, 2002 at 23:14 UTC
    Three things:
    • you say you're reading from a file, yet you're getting your input from '<>', which is stdin. that might be why you're not getting any data
    • you're using 'fixed-width' files, yet you're expecting each line to end in a newline. If 'fixed-width' == record based, then you should be doing a read($buffer, $record_length) and doing the regex on $buffer
    • the best way to pass data between subs is to pass arguments. Globals are evil (tm). The first line of get_domcf should be something like my $key = shift; and you should call get_domcf like so get_domcf($key)
    I think if you sort these bits out, you'll fix your problem :-)
      In the sub get_domkey I am reading from  <STDIN> this is not a problem, I am getting the key I want (the print statement is returning it). The sub get_domcf is where I am reading from a file. I will try to get rid of the globals and see if that helps, thanks for the reply ! Aseidas