in reply to Re: How to fill the space with comma while filehandling
in thread How to fill the space with comma while filehandling
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: How to fill the space with comma while filehandling
by davido (Cardinal) on Jan 23, 2014 at 07:50 UTC | |
Let's forget that you ever have (or assume that you never have) heard about regular expressions, and just look at how you might accomplish this with pencil and paper. Look at the first line of your input:
You want to place a comma in place of the space character after each of the first five fields. Or at a lower level (ignoring the abstraction of "fields"), you want to replace the first five space characters with commas. So on paper you would place your right index finger at the start of the line of text, and slide it rightward, scanning through the line of figures until you found the first space. Then you would write a comma there instead. Your right index finger keeps track of your current position in the line of text. Each time you find a space, you would raise one finger on your left hand, repeating the steps above until all five fingers of your left hand were extended, reminding you that you're done. Each time you advance to the next character in the text, you would slide your right index finger one place to the right, keeping track of where you are in the text. In a language like C, a string is really just an array with a \0 at the end. So you could translate your paper and pencil algorithm to C by writing a loop that walks through the c-string array one character at a time (moves your right index finger one character at a time), and each time it finds a space character, replacing it with a comma... five times (similar to how you would count with your left hand). If you want to be safe, you'll also detect the end of the line of text (or the c-string array), and stop early if you reach that without reaching five substitutions first. Perl's strings are a little higher level than that, but we still have tools to manipulate them one digit at a time. It may not be the most elegant way to get things done, but it's the way that is fundamentally most similar to how you would approach the problem with pencil and paper in everyday life. So let's implement that. If you want a Perlish, idiomatic solution without any work or effort of your own, you'll have to pay me. If you want a free solution, you'll have to indulge my desire to teach you something useful.
substr, perlsyn (loops). It also turns out that Perl offers a function called index, which would further simplify this process by allowing you to not keep track of the mechanics of advancing your position pointer. But it's not necessary to use that higher level just because it exists.. this solution works even if it's "baby Perl". Dave | [reply] [d/l] [select] |
| |