Geoff Ellis wrote: > Is there a way to dynaically set the variables in an unpack statement? > > What I want to do is read in a load of CSV's, unpack each line and insert > the data in a database.... > everything is easy except trying to do the small problem... > > here's my code in trying to genereate the unpack function.. > > <cut> > $dollar = sprintf("%c", 044); # creates $ symbol. > > # build up unpack variables using the amount of fields required. > my $i = 0; > while ($i < $importfiles{$file}[2]) { > $i ++; > $fieldstring .= "${dollar}field${i},"; > } > $fieldstring = substr($fieldstring, 0, -1); > print $fieldstring, "\n"; #<<<<<<<<<<<<<<<< this contains > ""$field1,$field2,$field3,$field4" > > > > # Step through the file and break each line down with unpack and insert > the info into the file. > foreach my $line (@filedata) { > ($$fieldstring ) = unpack ( $importfiles{$file}[0], $line ) ; > print "$field1 - $field2 - $field3 - $field4\n"; > } > </cut> > > Now, I know this doesn't work becuase $fieldstring is the variable populated > with the first value in the unpack... > How would I go about this in a way that works..
The first part (if I understand correctly) can be changed to (I had to generate my own data structures): use strict; my %importfiles; my $file = 'file'; $importfiles{$file}[0][0] = 'CCCC'; $importfiles{$file}[0][1] = 1; $importfiles{$file}[1][0] = 'CCCC'; $importfiles{$file}[1][1] = 1; $importfiles{$file}[2][0] = 'CCCC'; $importfiles{$file}[2][1] = 1; $importfiles{$file}[2][2] = 2; $importfiles{$file}[2][3] = 3; $importfiles{$file}[2][4] = 4; my $fieldstring = ''; for (my $ii = 1; $ii < @{$importfiles{$file}[2]}; $ii++) { $fieldstring .= "\$field$ii,"; } chop $fieldstring; # remove last ',' (not really needed) print $fieldstring, "\n"; # and then the 2nd part: my ($field1, $field2, $field3, $field4); my @filedata = ('f12345', 'abcdefg', 'hijklmn', 'opqrstuv'); foreach my $line (@filedata) { # I split this into 2 lines to simplify the eval and added a [0] # which seemed right for the data structure my @arr = unpack ($importfiles{$file}[0][0], $line); eval "($fieldstring) = \@arr"; print "$field1 - $field2 - $field3 - $field4\n"; } __END__ But I doubt I would recommend doing it that way. Almost always it's better to avoid evaling data into vrbl names. -- ,-/- __ _ _ $Bill Luebkert ICQ=14439852 (_/ / ) // // DBE Collectibles Mailto:[EMAIL PROTECTED] / ) /--< o // // http://dbecoll.tripod.com/ (Free site for Perl) -/-' /___/_<_</_</_ Castle of Medieval Myth & Magic http://www.todbe.com/ _______________________________________________ Perl-Unix-Users mailing list. To unsubscribe go to http://listserv.ActiveState.com/mailman/subscribe/perl-unix-users