Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling

Re^2: CSV file

by integral (Hermit)
on Oct 31, 2005 at 15:20 UTC ( #504289=note: print w/replies, xml ) Need Help??

in reply to Re: CSV file
in thread CSV file

([\,]) only matches a single non-comma character. It is missing a quantifier such as + or *.

Everytime I see (.*) I feel very uneasy, and usually I can think of a much simpler way to accomplish the same thing. In this case, all the regular expression is really doing is finding the first comma! Now, split normally splits on all the delimiters it finds in a string, but it can take an optional third argument which tells it exactly how much to split the line; in this case we just want two fields. As a bonus we can give the split fields names so we don't have to use $1 and $2.

while (<FILE>) { chomp; my ($name, $address) = split /,\s+/, $_, 2; print "$name lives at $address\n"; }

Another thing that would make me think twice about your solution is that you've got an if statement, but there's no sensible behaviour defined for when the if is false! Although I have to say that using a proper CSV module (Text::CSV, etc) is always preferable.

integral, resident of freenode's #perl

Replies are listed 'Best First'.
Re^3: CSV file
by Moron (Curate) on Oct 31, 2005 at 15:38 UTC
    I spotted the lack of * shortly after posting.

    re .*: having eliminated the first column and its delimiter, .* must be what is left over as the second and last column - why make the engine work harder?. It really is quite common that the remainder of a string is defined by elimination of specific features of the preceding characters and needs no further analysis - only when the .* is attempted earlier than such elimination is completed does it cause a problem.

    re "if" - I opted for this rather than allowing any exceptions to just fall through the code, whereas no else is defined because neither was any provision for such exceptions stated in the requirement. Not seeing the benefit of this turns out to be a trap for habitual negative thinking: If there was a blank line in the data, your own solution, which apart from not filtering exceptions is fine, would accept the blank data and, for example, enter it into the database!


    Free your mind

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://504289]
and one hand claps...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (9)
As of 2017-10-23 08:05 GMT
Find Nodes?
    Voting Booth?
    My fridge is mostly full of:

    Results (277 votes). Check out past polls.