richard90522 has asked for the wisdom of the Perl Monks concerning the following question:
I would like to write data driven tests with perl grep-method. When the search-regex is given directly everything behaves as expected. But as soon as I write the search-regex into a variable the _whole_ list is returned.
The result when running it:#!perl use strict; use warnings; use Test::More; use Data::Dumper; my @cities = qw( Berlin Budapest London Paris Praha ); # Data driven tests: my @grepper_tests = ( { wanted_regex => qr/B/, expected_nr_found => 2, }, # many more tests to come here... ); my @found_cities; my $expected_nr_found; for my $cur_test (@grepper_tests) { my $wanted_regex = $cur_test->{wanted_regex}; cmp_ok(ref($wanted_regex), 'eq', 'Regexp', 'Regex type ok: ' . $wa +nted_regex); $expected_nr_found = $cur_test->{expected_nr_found}; @found_cities = grep $wanted_regex, @cities; cmp_ok(scalar(@found_cities), '==', $expected_nr_found, "I have found: " . join(", ", @found_cities)); } # Single written tests: @found_cities = grep /B/, @cities; $expected_nr_found = 2; cmp_ok(scalar(@found_cities), '==', $expected_nr_found, "I have found: " . join(", ", @found_cities)); # as soon as the regex is in a variable the whole searched array # is the result my $wanted_regex = qr/B/; cmp_ok(ref($wanted_regex), 'eq', 'Regexp', 'Regex type ok: ' . $wanted +_regex); @found_cities = grep $wanted_regex, @cities; $expected_nr_found = 2; cmp_ok(scalar(@found_cities), '==', 2, "I have found: " . join(", ", @found_cities)); done_testing();
How can I write a grep-command with the expression saved in a variable? Thanks for your precious help, Horshack~/perltest_regex_in_array$ perl 100_regex_in_array.pl ok 1 - Regex type ok: (?^:B) not ok 2 - I have found: Berlin, Budapest, London, Paris, Praha # Failed test 'I have found: Berlin, Budapest, London, Paris, Praha' # at 100_regex_in_array.pl line 31. # got: 5 # expected: 2 ok 3 - I have found: Berlin, Budapest ok 4 - Regex type ok: (?^:B) not ok 5 - I have found: Berlin, Budapest, London, Paris, Praha # Failed test 'I have found: Berlin, Budapest, London, Paris, Praha' # at 100_regex_in_array.pl line 47. # got: 5 # expected: 2 1..5 # Looks like you failed 2 tests of 5.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Direct regex vs. regex stored in a variable
by LanX (Saint) on Apr 15, 2023 at 09:25 UTC | |
by richard90522 (Novice) on Apr 16, 2023 at 07:12 UTC |