2

This conditional must match either telco_imac_city or telco_hier_city. When it succeeds I need to extract up to the second underscore of the value that was matched.

I can make it work with this code

if ( ($value =~ /(telco_imac_)city/) || ($value =~ /(telco_hier_)city/) ) {
    print "value is: \"$1\"\n";
}

But if possible I would rather use a single regex like this

$value = $ARGV[0];
if ( $value =~ /(telco_imac_)city|(telco_hier_)city/ ) {
    print "value is: \"$1\"\n";
}

But if I pass the value telco_hier_city I get this output on testing the second value

Use of uninitialized value $1 in concatenation (.) or string at ./test.pl line 19.
value is: ""

What am I doing wrong?

2 Answers 2

1
while (<$input>){
    chomp;
    print "$1\n" if /(telco_hier|telco_imac)_city/;
}
Sign up to request clarification or add additional context in comments.

1 Comment

OP wants to return "only up to the 2nd underscore of the value that was matched" (ie, telco_hier_ or telco_imac_).
1

Perl capture groups are numbered based on the matches in a single statement. Your input, telco_hier_city, matches the second capture of that single regex (/(telco_imac_)city|(telco_hier_)city/), meaning you'd need to use $2:

my $value = $ARGV[0];
if ( $value =~ /(telco_imac_)city|(telco_hier_)city/ ) {
    print "value is: \"$2\"\n";
}

Output:

$> ./conditionalIfRegex.pl telco_hier_city
value is: "telco_hier_"

Because there was no match in your first capture group ((telco_imac_)), $1 is uninitialized, as expected.

To fix your original code, use FlyingFrog's regex:

my $value = $ARGV[0];
if ( $value =~ /(telco_hier_|telco_imac_)city/ ) {
    print "value is: \"$1\"\n";
}

Output:

$> ./conditionalIfRegex.pl telco_hier_city
value is: "telco_hier_"

$> ./conditionalIfRegex.pl telco_imac_city
value is: "telco_imac_"

2 Comments

What happens when $value is telco_imac_ ?
@FlyingFrog Edited with (a slightly amended version of) your regex, thanks! The original part of the answer is helpful for OP to understand why the uninitialized warning was occurring.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.