Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

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


Comment on Re^2: CSV file
Select or Download Code
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!

    -M

    Free your mind

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://504289]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (16)
As of 2014-12-18 16:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (58 votes), past polls