thank you Shawn. this works nicely for me.



________________________________
 From: Shawn H Corey <shawnhco...@gmail.com>
To: beginners@perl.org 
Cc: Rajeev Prasad <rp.ne...@yahoo.com> 
Sent: Saturday, September 28, 2013 8:49 AM
Subject: Re: formatting a list
 

On Fri, 27 Sep 2013 22:59:01 -0700 (PDT)
Rajeev Prasad <rp.ne...@yahoo.com> wrote:

> i want them to look neat, something like this: where they look in
> line. I do not know before hand how long each word would be....
> 
> abc____12____4567
> xy4z___xtr4__sdf
> PQRSDR_xcvf__scc234
> 
> how could i use the sprintf to obtain such an effect?

Try:

#!/usr/bin/env perl

use strict;
use warnings;

# --------------------------------------

my @data = ();
my @maxs = ();

while( <DATA> ){
  chomp;
  my @fields = split m{ _+ }msx, $_;

  for my $i ( 0 .. $#fields ){
    my $len = length( $fields[$i] );
    if( ( $maxs[$i] || 0 ) < $len ){
      $maxs[$i] = $len;
    }
  }
  push @data, \@fields;
}

for my $row ( @data ){
  my @fields = @$row;
  my $last = pop @fields;
  for my $i ( 0 .. $#fields ){
    my $len = length( $fields[$i] );
    print $fields[$i], '_' x ( $maxs[$i] - $len + 1 );
  }
  print $last, "\n";
}

__DATA__
abc_12_4567
xy4z_xtr4_sdf
PQRSDR_xcvf_scc234


-- 
Don't stop where the ink does.
    Shawn

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/

Reply via email to