1

I'm reading a file and processing according to the need. As the output has tables, few columns are misaligned. I'm using while loop for processing of input read file.

Regexp:

$_ =~ s/$var/$mod{$var}/;
print "$_";

Please suggest me better way to format the output.

col1 (40spaces) col2(nspaces) coln(nspaces)

Here it is how i done it: open(MYFILE,'log') while() { if(condition) my($var) = (split ())[]; $var =~ s/xyz/xy/; if($var = condition) $var = $1; } $_ =~ s/$var/$mod{$var}/; print "$_"

i need the output table 2nd column to be 40 spaces
3
  • Have you considered format? (more docs) Commented Jan 9, 2014 at 22:25
  • I use sprintf. What have you tried so far? Commented Jan 9, 2014 at 22:36
  • I'm totally beginner, so this is the first time im using output formatting. As the processing is done on the fly in a while loop and later using $_ for print, is there a way to format the output column ? Commented Jan 9, 2014 at 23:12

1 Answer 1

2

I would suggest rather than using s/// on the whole line, you should split the line into fields, do what you need with each field, then output a formatted line using printf. Something like this:

use strict;
use warnings;

sub trim { $_ = shift; s/(\A\s+)|(\s+\z)//gr }  # or use String::Trim

my %full_country_name = (
  ENG  => 'England',
  SCO  => 'Scotland',
  WAL  => 'Wales',
);

while (<DATA>)
{
  chomp;

  # Input columns are 4 chars, 5 chars, and everything else
  my ($number, $country, $letter) =
    map trim($_),
    m{^ (.{4}) (.{5}) (.+) $}x;

  # Output columns are 4 chars, 10 chars, and everything else
  printf(
    "%-4s%-10s%s\n",
    $number,
    $full_country_name{$country},
    $letter,
  );
}

__DATA__
1   ENG  A
2   SCO  B
3   WAL  C

Update: edited to include an implementation of the trim function.

Sign up to request clarification or add additional context in comments.

2 Comments

Im getting error saying can't locate string/trim.pm. is it version issue ?
Then install String::Trim, or write a replacement trim function. Something like sub trim { $_ = shift; s/(\A\s+)|(\s+\z)//gr }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.