in reply to Re: replace in lines
in thread replace in lines

It prints it, but it does not replace it in the line in the file.... Any other sujestions?

Replies are listed 'Best First'.
Re^3: replace in lines
by ikegami (Patriarch) on Aug 01, 2007 at 19:57 UTC

    True. Changing a variable in memory will not change a file. Except when using Tie::File which should be perfect for you.

    Normally, to change something in a file, you need to read the file, do your change, and write the file back out.

    use strict; use warnings; use POSIX qw( strftime ); use Text::CSV qw( ); use Tie::File qw( ); use constant INHOUSE =>"Open House Information"; { my $today = strftime('%Y/%m/%d', localtime()); tie(my @db, 'Tie::File', 'dbase1.exm') or die("Unable to open database: $!\n"); my $csv = Text::CSV->new(); foreach my $line (@db) { $csv->parse($line) or die("Unable to parse \"$line\"\n"); my @fields = $csv->fields(); my ($status, $date) = $fields[22, 23]; # Convert date to sortable format. my ($m, $d, $y) = split(/\//, $date); $date = "20$y/$m/$d"; my $kill = ($date < $today); # Are you sure this isn't backward +s? if ($status eq INHOUSE && $kill) { $status = ''; } # Reassemble the line and updated the file. $fields[22] = $status; $csv->combine(@fields) or die("Unable to recreate line from fields @fields\n"); # Changing $line causes the file to be updated. $line = $csv->string(); } untie @db; }

    If you're trying to remove the entire line, it's even easier:

    use strict; use warnings; use POSIX qw( strftime ); use Text::CSV qw( ); use Tie::File qw( ); use constant INHOUSE =>"Open House Information"; { my $today = strftime('%Y/%m/%d', localtime()); tie(my @db, 'Tie::File', 'dbase1.exm') or die("Unable to open database: $!\n"); my $csv = Text::CSV->new(); @db = grep { $csv->parse($line) or die("Unable to parse \"$line\"\n"); my @fields = $csv->fields(); my ($status, $date) = $fields[22, 23]; # Convert date to sortable format. my ($m, $d, $y) = split(/\//, $date); $date = "20$y/$m/$d"; $status ne INHOUSE || $date >= $today } @db; untie @db; }
Re^3: replace in lines
by snopal (Pilgrim) on Aug 01, 2007 at 19:39 UTC

    I find it interesting that you think this code sample actually writes data back to the file. Is there a part of the code you are not including?

    If that is the case, you may not realize that localizing $WW means that you lose the value of that variable when you leave the current scope (go beyond the encapsulating closing curly bracket).

    If you really intend to save the data back to the original file, you have a lot more work ahead of you. This code will have a number of pitfalls, including dropping the changed value before you write it, or writing to a file you are reading from before finishing the initial processing of the original contents.

    Messy!

      I can't seem to get it to go as suggested How would you do it using old file new file senario... I can't seen to find anything on on that anymore.