Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Pad filed zeros and concatenate two fileds as one 2

Status
Not open for further replies.

hello99hello

Programmer
Jul 29, 2004
50
CA
Hello All,

I am currently researching the following issues, and I was wondering if anyone has an input.

Basically, I have the following records ( with four fileds each, fileds 3 and 4 have varying lenght):

Jamie,Foxx,09,765
Look,Mann,87,5987

The projected output records should be:

Jamie,Foxx,00900765
Look,Mann,08705987

In summary, I want to pad the third fields with one or more leading zeros to make a three-character field. Also, I want to pad the fourth field with one or more leading zeros to make five-character field. Lastly, I want to concatenate third and fourth fields to one.

Here is my effort, This has to be done in array format:

# put the records in array
@array_file = <INPUT> ;
foreach $array_record (@array_file){
@array = split (",", $array_record) ;

#pad third element
$array[2]= array_pad($array[2], 2, 0);
$array[3]= array_pad($array[3], 5, 0);
$array[2]= $array[2].$array[3]= ;

$new_record = join ',', @array;
print OUTPUT "$new_record\n";

This does not produce the recquired output. I was wondering if anyone has other ideas.
 
Code:
#perl
use strict;
use warnings;

my @a1;
while (<DATA>) {
    chomp;
    my @temp = split(/,/, $_);
    push(@a1, [ $temp[0], $temp[1],
               pad($temp[2],3,"0") . pad($temp[3],5,"0")
              ]);
}

print "[", join(",", @$_), "]\n" for @a1;

sub pad {
    my ($str, $len, $char) = @_;
    $str =~ s/^/$char x ($len - length($str))/e;
    $str;
}

__DATA__
Jamie,Foxx,09,765
Look,Mann,87,5987

[b]Output:[/b]
[Jamie,Foxx,00900765]
[Look,Mann,08705987]
 
Actually, sub pad could be simpler:
Code:
sub pad {
    my ($str, $len, $char) = @_;
    $char x ($len - length($str)) . $str;
}
 
Or, getting really concise and cryptic:
Code:
#!perl
use warnings;

printf "[%s,%s,%03d%05d]\n", split /,/ while <DATA>;

__DATA__
Jamie,Foxx,09,765
Look,Mann,87,5987
Same output.
(No, I don't really recommend writing like this. [3eyes])
 
Extending the sprintf mechanism:
Code:
sub zpad {
    ($num, $width) = @_;
    return sprintf "%0*s", $width, $num;
}

foreach (1..10) {
    print zpad($_,3), "\n";
}
Cheers, Neil
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top