Operating System - HP-UX
1824976 Members
3390 Online
109678 Solutions
New Discussion юеВ

perl: file open / line modify... kept me up late..

 
Bill McNAMARA_1
Honored Contributor

perl: file open / line modify... kept me up late..

not sure this is _the_ perl forum, but I'll ask in any case..

I've the followin excerpt of a perl script, that is meant to read and modify data a file.

but it doesn't work of course..

#
# FILE originally contains following line
# one|two|three|0|1
# $q is one
#
open(FILE, ">$questionfile");
@correct = grep(/^\Q$q|\E/, );
close(FILE);
#
# FILE ends up blank
# should end up
# one|two|three|1|1
#
$q_line = $correct[0];
($aaa,$bbb,$ccc,$ddd,$eee) = split(/\|/, $q_line);
$fff =$ddd + 1;
$newline = "$aaa|$bbb|$ccc|$fff|$eee\n";
open(TMP, ">$tmp");
print TMP "$newline\n";
# ends up |||1|
close(TMP);


more or less, if there's a file that looks like this:

one|two|three|0|1
une|deux|trois|0|4
aon|do|tri|0|5

I want it to end up looking like this:
one|two|three|0|1
une|deux|trois|1|4
aon|do|tri|0|5

if the variable to search for, one, une, aon
is known and $q above..

Later,
Bill
It works for me (tm)
5 REPLIES 5
harry d brown jr
Honored Contributor

Re: perl: file open / line modify... kept me up late..

Bill,

Your first file, $question file, is open for output ">$question". You need the open the file for input "<$question".

live free or die
harry
Live Free or Die
Rodney Hills
Honored Contributor

Re: perl: file open / line modify... kept me up late..

You may want to put a "chomp @correct" after the line

@correct=grep...

Input lines from files have the \n on them, sometimes they can be ignored, but usually you don't want them.

-- Rod Hills
There be dragons...
harry d brown jr
Honored Contributor

Re: perl: file open / line modify... kept me up late..

Bill,
your problem is your grep statement. What are you looking for, because your grep is returning null??

live free or die
harry
Live Free or Die
harry d brown jr
Honored Contributor

Re: perl: file open / line modify... kept me up late..

Bill,

what are you trying to match on here:

@correct = grep(/^\Q$q|\E/, );

What is the "\Q" and "\E" for??

live free or die
harry
Live Free or Die
Leslie Chaim
Regular Advisor

Re: perl: file open / line modify... kept me up late..

Bill,

Just two points:
1. It appears to me that you need an exact match to the first column. Therefore, it is not a candidate for regex usage.
Use the eq operator instead:

@correct = grep $q eq $_, ;

You can include or omit the parens, Perl doesn't care:)

2. If all you need done is stated in your question, why not make use of Perl powerful command line interface:

perl -nalF'\|' -e "if (\$F[0] eq '$q') {\$F[3] +=1; print join '|', @F}" origfile > newfile

Assuming you have a shell variable $q set to somevalue.

Leslie
If life serves you lemons, make lemonade