Forum Moderators: coopster & phranque

Message Too Old, No Replies

More fun with shortcuts, replacing conditions with regexes

         

csdude55

5:09 am on Sep 3, 2021 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Let's say that I have something like this:

$foo = 'this is a test';

if ($foo) {
$_ = $foo;
s/ a / a bad /g;
}

elsif ($bar) {
$_ = $bar;
s/ a / a good /g;
}

else { $_ = false; }


I know that if it there were no conditions and I only had $foo then I could do this:

($_ = $foo) =~ s/ a / a bad /g;


And if it wasn't for the regexes then I could do this:

$_ = $foo //
$bar //
false;


The question is, is there a way to shorten this to a one liner and eliminate the conditions AND regexes?

I tried these, but both just return true or false:

# Test 1, tried with and without ( )
$_ = ($foo =~ s/ a / a bad /g) //
($bar =~ s/ a / a good /g) //
false;

# Test 2
$_ = $foo ?
$foo =~ s/ a / a bad /g :
$bar =~ s/ a / a good /g;


I know, I know... readability! LOL But this is mainly for my own education.

Brett_Tabke

1:59 pm on Jun 5, 2022 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



Off hand no, but have you ever played Perls Conditional Ternary Operator?

[perlmaven.com...]

csdude55

9:00 pm on Jun 9, 2022 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



You mean like I tried in Test 2?

$_ = $foo ?
$foo =~ s/ a / a bad /g :
$bar =~ s/ a / a good /g;


It's a good thought, but it only sets $_ to true or false instead of setting the internal values.

It's been a minute since I posted this, though, and I don't even remember what I was trying to improve now! LOL

Brett_Tabke

12:11 am on Jun 10, 2022 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



Ok, ya, I missed that. I read that as end of statement.

I started using Ternary conditionals all over the place.

I used to code:
$x="foo";
$x="bar" if $cheese;

but ternary makes so much more sense to me.

csdude55

3:50 am on Jun 10, 2022 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I agree. When it was first mentioned on here I was hesitant because it felt confusing and I focused on readability, but as I've been focusing on speed and performance lately I've gotten more used to it. And NOW it's second nature :-)