Forum Moderators: coopster & phranque

Message Too Old, No Replies

Shortcuts

         

csdude55

9:28 pm on Aug 18, 2021 (gmt 0)

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



I'm kinda out of practice with Perl, I've been focused on PHP for waaaay too long :-( I'm using Perl 5.16.3.

In PHP I've been using ? a bit; eg, $foo = $bar ? '';. Is this identical to $foo = $bar || ''; in Perl?

I'm specifically trying to shrink a bunch of lines like:

if (!$foo) { $foo = ''; }

Any other nifty shortcuts that I should know about?

csdude55

9:38 pm on Aug 18, 2021 (gmt 0)

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



Or wait... what are the rules on this one again?

$foo //= '';

phranque

3:50 am on Aug 19, 2021 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



demonstrations of nifty code are cool but i prefer to focus on readability.

csdude55

4:26 am on Aug 19, 2021 (gmt 0)

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



When it comes to my Perl scripts, I usually think the same. I mostly use PHP for display and Perl for processing, so speed isn't AS critical with Perl. This means that I can stand to live with a little bit of bloat there.

But it was only a year or two ago that you guys showed me ? and $foo = $blah ? $lorem : $ipsum, and now I can read them just as clearly as anything else. So I figure that I might as well learn whatever exists, and if it's easier than great! If not, no biggie.

So as far as I can tell, these are essentially the same:

if (!$foo) { $foo = 'bar; }
$foo = $foo ? $foo : 'bar';
$foo = $foo // 'bar';
$foo //= 'bar';


Using $foo = $foo || 'bar'; is similar, but apparently not exactly the same:

[perldoc.perl.org...]

csdude55

6:13 pm on Aug 19, 2021 (gmt 0)

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



Am I correct that these are identical?

# old
if ($arr{'checkid'}) { $val = $arr{'checkid'}; }
elsif($foreign && !$val) { $val = 'foreign'; }
else { $val = '1'; }

# new
$val = $arr{'checkid'} //
($foreign && !$val) ? 'foreign' : '1';


Preliminary tests show the same result.

At this point this is just an exercise, but it cuts the code in half. So if I'm right that they're the same then I think I could easily get used to the second version.