in reply to Getting element of array with a match
While grep is handy it it not efficient as you always search the whole array even if you find a match in the first element. Assuming your '100X' are unique product ids this is probably the most efficient way (although by no means the only way) to do it (the last means we stop searching at the first match. If we find a match string will be defined. If there is not match it will be undef. If you have comma separated data split will work fine. Substring works on the assumption of fixed width records so if someone enters say '1010  ' you would end up getting ' ,string' back which is not what you want. The correct syntax to get all the stuff after 5 chars (4 digits and the comma) is $string = substr $line, 5;
Your grep is broken because when you say $scalar = grep... you get the number of matches not the actual array elements(s). If you call grep in array context @ary = grep... then you get an array of all the elements that matched - if there is only one it will be $ary[0]. Many functions in perl exhibit this schizophrenic behaviour - it is called scalar/array context.
my @ary = <DATA>; my $find_id = 1006; my ($code, $string ); for my $line( @ary ) { next unless $line =~ m/^$find_id/; chomp $line; ( $code, $string ) = split ',', $line; last; } if ( $string ) { print "Found '$string'\n"; } else { print "No match!\n"; } __DATA__ 1001,choochoo 1002,candycane 1003,sockpuppet 1004,choochoo 1005,candycane 1006,sockpuppet6 1007,foo 1008,bar
cheers
tachyon
s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print
Fixed errant [] chars dvergin 2002-12-23
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Re: Getting element of array with a match
by Arien (Pilgrim) on Dec 24, 2002 at 04:18 UTC | |
by tachyon (Chancellor) on Dec 24, 2002 at 04:40 UTC | |
by Arien (Pilgrim) on Dec 24, 2002 at 05:04 UTC | |
by tachyon (Chancellor) on Dec 24, 2002 at 05:18 UTC |