Check if exists in perl returning always true

perl

Solution

It always returns true because you have misunderstood how to pass arguments to a subroutine. When you do this:

my @entityarray = @_;
my $entity = $_[1];

You assign all of the arguments to `@entityarray` and the second argument to `$entity`. So of course if you check all elements of one against `$entity` it will be one of them.

You also should not use prototypes, the parentheses that follow the sub name. Unless you know what they do, they are best ignored, as they have a very special functionality.

The solution, reverse the arguments:

check_if_entity_exists($foo, @bar);
...
sub check_if_entity_exists {
    my $entity = shift;     # the first arg
    my @entityarray = @_;   # the rest

This happens because perl flattens the array when it is passed as an argument, so it becomes just elements in the argument list, not a single variable. Perl has no way of knowing whether you passed an array or not. Unless you play around with prototypes. Which I do not recommend other than as an exercise. If you do something like:

sub foo (\@$) {

Then you can actually pass an array as an argument, much like `push` and `shift`.

You can also pass the array as a reference, in which case you do something like so:

foo(\@array, $var);

sub foo {
    my $aref = shift;    # @$aref is now @array
    my $var  = shift;

In this case, you need to beware that you are using the same array that you passed to the subroutine, not a copy. So if you change it, changes are permanent.

Note: As PSIAlt points out, you should not use an arbitrary string directly in a regex, if your intent is to match literally. There may be meta characters in it that cause side effects. Do either:

grep /^\Q$entity/, ..       # quote meta characters
grep { $_ eq $entity } ...  # check string equality

as PSIAlt suggests, `eq` is the most straightforward solution, and unless you need regex power, should probably be the one you use.

Problem

I have a subroutine in perl to check if array contains particular element if it contains return TRUE else false..The below code should retun false since the searched element http_TestABC is not in array but still it returning TRUE.Not able to figure why this happens.Any pointers appreciated Thanks ``` #!/usr/bin/perl use strict; use warnings; my @result_listosp; # defines an empty array $result_listosp[0] = "origin-server-pool-1"; # array has one element $result_listosp[1] = "http-pool-OSP2"; # array has 10 elements now my $osp="http_TestABC"; my $status_osp_check= check_if_entity_exists(@result_listosp,$osp); print $status_osp_check; sub check_if_entity_exists() { my @entityarray = @_; my $entity = $_[1]; my $status="FALSE"; if ( grep( /^$entity$/, @entityarray ) ) { $status="TRUE"; return $status; } else { return $status; } } ```

Original source