Stuart Clemons wrote:
>
> Help. I'm a frustrated newbie who wants to use Perl to make my life easier.
>
> The following simple task is only one small part of a program I'm trying to
> put together to automate some things I currently do manually.
>
> I have a file whose format looks like this:
>
> name1          name2          name3
> name4          name5          name6, etc.
>
> The names are separated by spaces.   I need the names to be one name per
> line, like this:
>
> name1
> name2
> name3, etc.
>
> I currently use a macro with a text editor to clean up the file into the
> one name per line format.  I can do this very quickly in contrast to the
> the last two hours I've spent trying to figure out how to get Perl to do
> this very simple task.  Arrggh !
>
> To simply things, I just tried to take the following string and print it
> out one name per line.
>
> my $x = "name1     name2     name3";
>
> I've tried various schemes using regex's and the ///s operator.  Most of
> the time I get syntax errors and the few times I get anything to work, it's
> not what I want.
>
> I did get this array structure to work:
>
> my @names = qw(name1     name2     name3);
> print "$names[0] \n";
> print "$names[1] \n";
> print "$names[2] \n";
>
> So I then spent time unsuccesfully trying to figure out how to get my
> string split into the array. I couldn't get that to work either. More
> Arrggh !
>
> Anyway, any help at this point will be appreciated.  I'm hoping that in the
> long run the time I spend learning Perl will pay off, which it will if I
> can automate some of the tasks I do manually (with the help of macros in a
> text editor).
>
> My next Perl task after I get my list of one name per line, is to sort the
> list and eliminate duplicate names.

Hi Stuart.

A lot of people have posted the solution

  split /\s+/, $string;  # or similar

which is fine, but has the pitfall that if $string
contains leading spaces then it will return an initial
empty field. The special case

  split ' ', $string;  # (which is also the default)

returns just a list of all sets of contiguous
non-whitespace characters in $string, which is probably
what you want. If your data is well-behaved and never has
any leading whitespace then the two are identical, but
it's something to beware of as it can cause obscure bugs.

HTH (somebody at least)

Rob






-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to