[Chicago-talk] Limiting a hash, or producing an interesting list

Steven Lembark lembark at wrkhors.com
Tue Nov 25 10:22:27 CST 2003



-- Jay Strauss <me at heyjay.com>

> Hi,
>
> I'm not sure how best to explain what I want to do.  the code below does
> what I want, but it seems needlessly complicated.  I figure there is
> probably a nice clean way to do this is less steps but I don't see it:
>
> Essentially, I have a list of all the fields "@all", and I want to
> produce a list of only the fields I'm interested in, and their position
> in the original list
>
> my @all = wq/this that other some junk trash need/;
> my %all;
> my @all{@all} = (0..$#all);
>
> my @interesting = qw/this that need/;
> my %interesting;
> @interesting{@interesting} = delete @all{@interesting};

Convert the header to a hash of name => offset and slice
the hash for the list of offsets that matter to you:

	my @interesting = qw( what you knead );

	my @header = qw( what you get );

	my %fieldz = map { $header[$_] => $_ } ( 0..$#header );

	my @offsetz = grep { defined } @fieldz{@interesting};

Nice thing about this approach is that you can easily change
the order that between @header and @offsetz. This gives you
a buffer between input field ordering since you can always
get the header fields out in order by name.

--
Steven Lembark                               2930 W. Palmer
Workhorse Computing                       Chicago, IL 60647
                                            +1 888 359 3508



More information about the Chicago-talk mailing list