http://qs321.pair.com?node_id=774957

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi perlmonks,

I would like to create a file and write the information in a proper position in a file. The below code is working fine, but I am looking for a good code.

The iput data is under __DATA__ section
my requirement is to write first value starting from position 1 to 10, second value should start from 11th position to 17th and third should start from 18th to 25th position.

Can anyone please help to write a good code in perl.

open(A,">Result.txt"); while(<DATA>) { my($one,$two,$three)= split(/\s+/,$_); my $delim=' '; my $one1=length($one); my $two1=length($two); my $three1=length($three); my($one2,$two2,$three2); if($one1 < 10) { my $one11= (10-$one1); my $fdelim=$delim x $one11; $one2=$one.$fdelim; } if($two1 < 7) { my $two11= (7-$two1); my $fdelim=$delim x $two11; $two2=$two.$fdelim; } if($three1 < 8) { my $three11= (8-$three1); my $fdelim=$delim x $three11; $three2=$three.$fdelim; } print A "${one2}${two2}${three2}\n"; } close(A) __DATA__ The Early Year Five New Swine

Thanks

Replies are listed 'Best First'.
Re: File Formatting - Help required
by cdarke (Prior) on Jun 26, 2009 at 08:28 UTC
    use strict; use warnings; open(A,">Result.txt") or die "$!"; while(<DATA>) { printf A "%-10s%-7s%-8s\n",split } close(A) __DATA__ The Early Year Five New Swine
    Update: The default arguments to split are sufficient: split $_ around whitespace.

    The format string (first argument) to printf is as follows:
    % indicates the start of a format specifier, a value which follows the format string will be "plugged-in" and formatted into this position.
    - means left justify the field
    10 (or 7 or 8) is the minimum field width. Shorter fields will be padded with spaces, longer will be displayed intact (data will not be lost).
    s indicates the field is a string
Re: File Formatting - Help required
by citromatik (Curate) on Jun 26, 2009 at 08:22 UTC

    You can use pack:

    use strict; use warnings; open(A,">Result.txt"); while (<DATA>){ chomp; my ($one,$two,$three) = split /\s+/; print A pack ("A10",$one); print A pack ("A7",$two); print A pack ("A8",$three); print A "\n"; } close(A); __DATA__ The Early Year Five New Swine

    citromatik

      You forgot use autodie; :)
      Thanks a lot for your help.