how to extract data from a table into a fixed length file

Hi,

I have to extract data from table A. Now A has about 200 columns. Now when I am writing data out into a file, every field should have a pre-specified length. How should I do it in perl?  Any ideas?

like for example -  column id should be 10 characters, name should be 30 characters and address should be 40. So in the output file, name should start from 11th position and address from 1st position

Regards,
Sayantan
sunny82Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

sunny82Author Commented:
I mean address from 41st position
0
tel2Commented:
Hi Sunny,

You can use the 'printf()' function for formatted printing.  For example:
    $id = 123;
    $name = 'My Name';
    $address = 'My Address';
    printf("%10s%-30s%-40s", $id, $name, $address);

Note:
- 's' is for strings
- '-' is for left justification.

Or, if you prefer to assign the output to a variable, you can use 'sprintf()', like this:
    $output = sprintf("%10s%-30s%-40s", $id, $name, $address);

You can also print directly to your output file, as you would with a normal 'print'.

For more help on these functions, type:
    perldoc -f printf
and:
    perldoc -f sprintf
and here's some useful info:
    http://www.sunsite.ualberta.ca/Documentation/Misc/perl-5.6.1/pod/perlfunc/sprintf.html
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
sunny82Author Commented:
Hi,

Many thanks for your response. I used that and it works fine. But the problem is, I have over 200 columns in the table and for each column, I have to write sprintf("%10s%-30s%-40s", $id, $name, $address), corresponding to their widths, which becomes very unwieldy and difficult to maintin.

Is there a way to use config file such that I only need to change the config file once(if there is any field width change in any column) and I can generate the file accordingly?

The config file should just have column name and its width.
0
Cloud Class® Course: CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

tel2Commented:
If you put fields in this format in a file called config.txt:
id,10
name,30
address,40

Open in new window

You could then do your processing like this:

open CONFIG, "<config.txt" or die "Can't open config file!";
while (<CONFIG>)
{
        chomp;
        ($name, $length) = split(',');
        $format .= "%${length}s";   # This will left-justify all fields
}

# Populate the @values array with the column values of a
# a row of your table.  I'll just hard code it here, but you
# will probably read a record from the table.
@values = (123, 'My Name', 'My Address');

printf($format, @values);

Open in new window

;
0
sunny82Author Commented:
I am getting the output like this

%10 s%30 s123


below is my code

use strict;

my $core_config = "$ENV{'CFG'}/menir-core-config-test.txt";
my $name;
my $length;
my $format;

open CONFIG, "<$core_config" or die "Can't open config file!";
while (<CONFIG>)
{
        chomp;
        ($name, $length) = split(',');
        $format .= "%${length}s";   # This will left-justify all fields
}

my $outfile = "$ENV{'DATA'}/CORE.txt";

my @row = (123, 'My Name', 'My Address');
printf($format, @row);
----------------------------------------------

this is my config ->

id,10
name,30
address,10
0
tel2Commented:
Hi Sunny,

Your version of the code works for me.  All I changed was:
    my $core_config = "$ENV{'CFG'}/menir-core-config-test.txt";
to:
    my $core_config = 'config.txt';
so it would work in my environment, and I got this output:
       123                       My Name                              My Address

Open in new window


Question:
Does my version of the code work for you (if you just copy/paste it from my previous post)?

tel2
0
FishMongerCommented:
Specifying the field width as part of the csv data is ok, but doesn't scale well.

A better approach would be to use an actual config file for the format specification.  There are a number of config modules to choose from on CPAN.  Here's an example using a YAML module/format.

config.yml
fields:  # list of fields in desired order
    - id
    - name
    - address
    - salary

---  # field format specifications
id:
    width: 10
    justify: '-'
    type: d

name:
    width: 30
    type: s

address:
    width: 30
    type: s

salary:
    width: 12
    type: f
    precision: .2

Open in new window


Test script:
#!/usr/bin/perl

use 5.010;
use strict;
use warnings;
use YAML::Tiny;

my $conf   = YAML::Tiny->read( 'config.yml' );
my $fields = $conf->[0]{fields};
my $format;

foreach my $field ( @$fields ) {
    no warnings 'uninitialized';

    $format .= '%' . $conf->[1]{$field}{justify}
                   . $conf->[1]{$field}{width}
                   . $conf->[1]{$field}{precision}
                   . $conf->[1]{$field}{type};
}

my @row = (123, 'My Name', 'My Address', 12.5);
printf($format, @row);

Open in new window


Output:
D:\test>sunny82.pl
123                              My Name                    My Address       12.50
0
sunny82Author Commented:
Hi,

Sorry for replying a bit late.

@tel2: The output I am getting is "%10 s%30 s       123"

The code is exactly the same as your code, word to word.

Is it because of tis statement ?

$format .= "%${length}s";   # This will left-justify all fields

@FishMonger: @INC does not have YAML::Tiny. Can we use some other module?
0
tel2Commented:
Hi Sunny,

"> The code is exactly the same as your code, word to word."
Perhaps, but the code you pasted above is not the same as mine.
Please copy/paste my code to your machine (again), run it, then copy/paste my code and the results here for analysis.

"> Is it because of tis statement ?
> $format .= "%${length}s";   # This will left-justify all fields"

Dunno.  That statement works in my Perl 5.10 Linux environment I'm using, in both your version and my version of my code.

I doubt this is an issue, but what version of Perl are you using?  Type "perl -v" and paste the output here.

Thanks.
tel2
0
tel2Commented:
What operating system are you running, Sunny?  I'm assuming UNIX/Linux, below.

Further to my post above, here's an alternative way to write that format line (line #6 in my 2nd post):
    $format .= '%' . $length . 's';
If that doesn't work in my script, please run each of the following one-liners from the Linux command line, and post the command and the output here:
    perl -e '$length=12;$format .= "%${length}s";print $format'

    perl -e '$length=12;$format .= "%" . $length . "s";print $format'

When you copy/paste my code back here for analysis (see my last post for details), please use this UNIX/Linux command to display the code before copying it:
    cat -vet the-script-name-of-my-version-of-the-code.pl
Hopefully that will show if there have been any strange characters inserted during the copy/paste to your system.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Perl

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.