[EMAIL PROTECTED] 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.

If the names don't include embedded spaces (i.e. all the whitespace is
delimiters), you can use the default split()
function for this:

   while(<>) {
       print "$_\n" for split;
   }

The perl one-liner for this would be:

   $ perl -lne 'print for split' myfile.txt

...
> 
> My next Perl task after I get my list of one name per line,
> is to sort the
> list and eliminate duplicate names.

Let's take it step by step. Consider:

   @arr = <>;

This reads all the input lines into an array. But we really want to split
each line into the separate names, so we use map for this:

   @arr = map split, <>;

Sorting is trivial:

   @arr = sort map split, <>;

Eliminating duplicates can be done through a standard trick:

   @arr = do { my %seen; grep !$seen{$_}++, sort map split, <> };

Now @arr contains the unique names, in sorted order, ready to print out.

The perl one-liner would be:

   perl -le 'print for grep !$seen{$_}++, sort map split, <>' myfile.txt

n.b., moving the sort from where it is to in front of the grep would be more
efficient if the number of duplicates is large.

HTH

-- 
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