Link to home
Start Free TrialLog in
Avatar of MatthewF
MatthewFFlag for Afghanistan

asked on

Read and write to a file

I have a file I need to read and write to. The file is pound (#) delimited and it contains a list of filenames and 5 sets of numbers, ie

Tom#$120,200#$154,001#$121,234#$234,123#$345,123
John#$123,200#$188,061#$134,254#$244,155#$333,133
Etc&

I need to do a few things:

Open this file and check is a previously set variable $input_file is any of the first field,
If  true check is another previously set variable, $figure is equal to any of the 5 sets of numbers.
If true print out a statement $figure is equal to previous figure

If not true pop off the first figure and write the new number to the end of the line.

For example

If the input file was Tom and the figure was 121,234, just a print out statement $figure is equal to previous figure

Or

For example if the input file was John  and the figure was $677,061,  the new line for John would be
John#$188,061#$134,254#$244,155#$333,133#$677,061
ASKER CERTIFIED SOLUTION
Avatar of Adam314
Adam314

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of mjcoyne
mjcoyne

I'm a little confused about what you're trying to do -- you say you only have one pound delimited file to read, but then speak of "If the input file was Tom..." and "...if the input file was John...".  See if this is close:

#!/usr/bin/perl -w
use strict;

my (%data, @order, $match);

#my $figure = '$121,234';
#my $person = 'Tom';

my $figure = '$677,061';
my $person = 'John';

open (IN, "org_file.txt") or die;
while (<IN>) {
    my @line = split /#/;
    chomp (@line);
    push @order, $line[0];
    $data{$line[0]} = [@line[1 .. $#line]];
}

if (exists $data{$person}) {
    for (@{$data{$person}}) {
        if ($_ eq $figure) {
        $match = $figure;
        }
    }
    if ($match) {
        print "$person already has $match\n";
    } else {
        $data{$person}[-1] = "$figure";
    }
}

open (OUT, ">new_file.txt") or die;

for (@order) {
    print OUT "$_#", join ("#", @{$data{$_}}), "\n";
}

You need to give it the person you want and the figure you're looking to match.  If, for example, you feed it:

my $figure = '$121,234';
my $person = 'Tom';

It prints out "Tom already has $121,234", and org_file.txt and new_file.txt are identical.  If instead you feed it:

my $figure = '$677,061';
my $person = 'John';

It doesn't print out anything, but new_file.txt becomes:

Tom#$120,200#$154,001#$121,234#$234,123#$345,123
John#$123,200#$188,061#$134,254#$244,155#$677,061

while org_file.txt remains:

Tom#$120,200#$154,001#$121,234#$234,123#$345,123
John#$123,200#$188,061#$134,254#$244,155#$333,133

Is this close?