Apply replace with first element returned by grep

I have this program

sub f {                                                                                                                                                                                                                       
    return ("A/X", "B/X");                                                                                                   
}                                                                                                                            

$x = grep( /X$/, f() ) =~ s/\/X$//r;                                                                                           
print "$x\n";                                                                                                                

($x) = grep( /X$/, f() ) =~ s/\/X$//r;                                                                                         
print "$x\n";                                                                                                                

( ($x) = grep( /X$/, f() ) ) =~ s/\/X$//;                                                                                        
print "$x\n";                                                                                                                

($x) = grep( /X$/, f() );                                                                                                      
$x =~ s/\/X//;                                                                                                               
print "$x\n";

Result

2
2
A/X
A

As a result i want

A

but makes only the last attempt.

In my complete program, I want to do this with a single line, since I have to do this many times. I want to avoid things like $x[0]and f()- a much more complex function

How can i do this?

+4
source share
1 answer
my ($x) = map { s{/X$}{}r } grep { /X$/ } f();

or

my $x = ( grep { /X$/ } f() )[0] =~ s{/X$}{}r;

or

use List::Util qw( first );

my $x = ( first { /X$/ } f() ) =~ s{/X$}{}r;

The first silently sets $xto undefif f()it returns nothing, and the other two are set $xto an empty string with a warning in this situation. The second avoids unnecessary work. The third avoids even more.


Aside, you asked for the equivalent of the following

my ($x) = map { s{/X$}{}r } grep { m{X$} } f();

, :

my ($x) = map { s{/X$}{}r } grep { m{/X$} } f();

, !

my ($x) = map { my $s=$_; $s =~ s{/X$}{} ? $s : () } f();

use File::Basename qw( fileparse );

my ($x) = map { my ($fn, $dir_qn) = fileparse($_); $fn eq 'X' ? $dir_qn : () }  f();
+5

Source: https://habr.com/ru/post/1692217/


All Articles