Barry Brevik wrote:
> I'm working on a project that receives an array of data that looks like
> this (example):
>
> @fieldspecs = qw
> (
> JobNum 14
> ProjectID 25
> PartNum2 50
> ProdQty13 15.2
> );
>
> The array is a definition of fields in a file; the fieldname followed by
> the field width. The fieldname frequently contains digits. When I get
> the data, it is text so I put it in an array (like you see above)
> because it is important to reference the fieldnames in the order I
> receive them. The array ALWAYS has a fieldname followed by the width,
> the the number of elements is always divisible by two.
>
> However, I also want to access the data as a hash so that for a given
> fieldname I can easily grab the width.
>
> It is easy enough to convert this array to a hash, but...
>
> ...is there a Perl-ish way to either ram the *fieldnames only* into a
> new array, OR, delete the field widths from the array leaving only the
> fieldnames??
One way you could do it is by using a counter variable inside of a grep
block, like so:
my $n;
my @fieldnames = grep { $n++ % 2 == 0 } @fieldspecs;
You mentioned that your project "receives" the data, so I wonder if
there's a point in your program where you're stuffing it into the
@fieldspecs array.
If there is, you could maintain two arrays:
my $input = "JobNum 14\n ProjectID 25 \n PartNum2 50\n";
my @names;
my @widths;
foreach (split /\n/, $input) {
my ($name, $width) = /(\w+)\s+([\d\.]+)/;
push @names, $name;
push @widths, $width;
}
Then, the indexes for the names and widths will match up, and you can do
things like
for my $i (0..$#names) {
my $name = $names[$i];
my $width = $widths[$i];
# do whatever here
}
Chris Prather wrote:
> my %names = (@fieldspecs);
> my @names = keys %names; # works if the files are *always* evenly paired
The problem with this is that it doesn't preserve order.
$ perl -le 'my %names = qw(a 1 b 1 c 1); print join(", ", keys %names);'
c, a, b
Hope that gives you some options!
--
Mike Gillis
ActiveState Software
_______________________________________________
ActivePerl mailing list
[email protected]
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs