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

OK, here is my function for splitting text at commas. However it is not working. Could someone please help? The script is to take one file, strip the commas out and copy to a new file.
There are four columns that will be split on commas.

$file = 'u:\curtisbl\test\text.dbf'; $file0 = 'u:\curtisbl\test\output.dbf'; $warn = "Unable to open file: $file\n"; $warn0 = "Unable to create output file: $file0\n"; $warn1 = "Unable to close file: $file\n"; $warn2 = "Unable to close output file: $file0\n"; open(FILE, "$file") || die $warn; open(TEXT, ">$file0") || die $warn0; while (<FILE>) { ($description, $UIC1, $UIC2, $UIC3) = split(/,+/); print TEXT; } close(FILE) || die $warn1; close(TEXT) || die $warn2;
Thanks,
Curtisb

Replies are listed 'Best First'.
(jeffa) Re: split function
by jeffa (Bishop) on Nov 12, 2001 at 22:05 UTC
    This is better as a Perl one-liner:
    perl -i.bak -pe 's/,//g' comma
    Now the file comma will have the commas removed and the original file is copied to comma.bak

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    F--F--F--F--F--F--F--F--
    (the triplet paradiddle)
    
Re: split function
by arhuman (Vicar) on Nov 12, 2001 at 22:10 UTC
    Jeffa has the answer, but just for you to know :

    change
      print TEXT;
    to
      print TEXT "$description $UIC1 $UIC2 $UIC3\n";

    You're currently printing $_ (ie what you're reading !) that's why there's no change...


    "Only Bad Coders Code Badly In Perl" (OBC2BIP)
      This will give blank lines (if on UN*X). He isn't chomping so $UIC3 already has a newline...

      <bold>UPDATE</bold>: Originally neglected to negate the conjugated to be

Re: split function
by belg4mit (Prior) on Nov 12, 2001 at 22:13 UTC
    ($description, $UIC1, $UIC2, $UIC3) = split(/,+/); print TEXT;
    print with just a handle prints the value of $_ which is in this case the original line you read. Try print "$description $UIC1 $UIC2 $UIC3";

    Although if all you really want to do is remove commas try doing this one liner: perl -pi~ -e 'tr/,//d'. This will tell perl to run the -e for every line and edit it in place (making a backup with a ~ appened to the filename).