Hi all, I am trying to split a file on whitespace and thankfully I tried my code with various examples of columns as I found out it only works for column 1 :(
#!/usr/bin/perl use warnings; use strict; my %splitting; open my $FILE, '<', 'input_file' or die $!; while (<$FILE>) { chomp; my @columns = split ' '; $splitting{$columns[0]} = [@columns[1 .. $#columns]]; print "@columns[3] \n"; } close $FILE;

So if I print column 1 then it works fine, but it seems that some of my columns aren't whitespace separated but the numbers are stuck together like so: let's say first column is 15,567 and then second column is -25,324 and then third column is -45,234, this in some cases is written as:

15,567 -25,324-45,234

(no white space between columns 2 and 3)

This creates a problem and of course returns errors. How can I work around this? I hadn't realised that the columns aren't always space delimited as I'm working with files with over 100,000 lines so couldn't check them all. I tried reformatting the file with an awk line I use quite a lot (awk '{printf "%-5s %25s %-5s \n", $1, $2, $3 }' - used "25s" just as an extreme number to easily see what's happening with my columns) but it doesn't help because again the file has to be space delimited.

Do you have any ideas about how I could reformat my columns so that they have a consistent style? I mean, I know how to use printf but the problem now is that I don't know how to tell perl where each column finishes and the next one begins.


In reply to problem with splitting file on whitespace: how to circumvent inconsistent formatting through file by angela2

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.