perl

Find matches beginning of string


Consider the following code:

my @Array = ("Case Number: CV-24-987654", 
    "Case Title: BIG NATIONAL BANK vs. IMA N DEFAULT, ET AL.", 
    "Case Designation: FORECLOSURE MARSH. OF LIEN", 
    "Filing Date: 08/10/2024", 
    "Judge: WILL RULE", 
    "Mediator: N/A",
    "Next Action: N/A", 
    "Last Status: INACTIVE",
    "Last Status Date: 10/04/2024", 
    "Prayer Amount: \$115,958.65");
    
    my $index = grep { $Array[$_] eq 'Prayer Amount:%' } 0 .. $#Array;
    
    print "My Index Number Is: $index\n";
    

I only need to match the beginning of the string to find the element position that contains the phrase "Prayer Amount:" I tried using a wild card % but it still returns 0.

How can I improve on this code?


Solution

  • First, note that you need to force list context on grep, otherwise it would return the number of matches rather than the matching elements. This can be achieved by enclosing the LHS of the assignment in parentheses:

    my ($index) = grep ...
    #  ~      ~
    

    or by slicing only the first result from grep:

    my $index = (grep { ... } 0 .. $#Array)[0];
    

    Instead of grep, you can use first from List::Util. It always returns a single element, so no such syntactical tricks are needed.

    use List::Util qw{ first };
    
    my $index = first { ...
    

    There are no wildcards when comparing with eq. You can use index to find a substring instead:

    my ($index) = grep {  0 == index $Array[$_], 'Prayer Amount:' } 0 .. $#Array;
    

    Or, you can use a regular expression:

    my ($index) = grep {  $Array[$_] =~ /^Prayer Amount:/ } 0 .. $#Array;
    

    ^ only matches at the beginning of the string.