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


In reply to Re: Getting element of array with a match by tachyon
in thread Getting element of array with a match by peppiv

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.