Larry Sandwick wrote:
>
> I have a scripted I wrote that uses *substr* on a file that has fixed
> fields. I have to parse the file before I upload into MYSQL.
>
> Is there a more efficient way other than *substr*, I looked a *pack* and
> *unpack* . it did not make any sense to me.
>
> Here is my code, and any suggestions, comments would be appreciated!!!
> #-----------------------------------------------
>
> #!/usr/bin/perl -w
> # Sample input file
> #       304 THE CASTLE TWO DRAWER CHEST  6-168  02/18/04
> #       751 FRUIT STILL LIFE PLANTER     6-22   02/18/04
> #      1029 GLASS TOP: 24" DIA X 1/2"    ----   02/18/04
>
> $pvr = 'DISCSL.txt';
> $out = 'DISCSL_out.txt';
>
> open FILE, "<$pvr" or die "Unabel to open the file\n";
> open DATA, ">$out" or die "Unabel to open the file\n";
>
> while(<FILE>)
>       {
>       $the_line = $_;
>       chomp($the_line);
>
>             $item     = substr($the_line,0,10);
>             $ldesc    = substr($the_line,11,40);
>             $page     = substr($the_line,52,6);
>             $d        = substr($the_line,59,8);
>
>       # Remove  all spaces we do not need !!!
>       $item =~ s/\s+// ;
>       $page =~ s/\s+// ;
>
>        if ( $page eq "----" ) { $page = "" };
>       print DATA "$item|$ldesc|$page|$d\n";
>
> }
>
> close FILE;
> close DATA;
>
> exit;

Hi Larry.

You need to use

  my ($item, $ldesc, $page, $d) = unpack 'A10xA40xA6xA8', $the_line;

but I make the $ldesc field 28 characters long instead of the 40 you have
codede, so perhaps you need a format of 'A10xA28xA6xA8'?

The 'A' unpack format strips trailing spaces from the input string so you
don't need to adjust the $page value afterwards. One the other hand, if
you want the fields exactly as they are, spaces and all, then use a lower
case 'a' format instead.

I hope this helps,

Rob




-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to