what does perl operator “||=” do?

后端 未结 4 1324
逝去的感伤
逝去的感伤 2021-01-29 12:32

What does the operator ||= do in perl?

to be more specific if you have a code like:

my ($my_link);
$my_link  ||= DownloadF($file,\'l\') if          


        
相关标签:
4条回答
  • 2021-01-29 13:01

    It assigns only if variable evaluates to false value. In each of your example lines, $my_link will only be assigned if the condition $s->{..} is true.

    0 讨论(0)
  • 2021-01-29 13:10

    it means if $my_link is nil/has no value, then assign it this value with = (value)

    if $my_link already has a value, then it don't do anything

    0 讨论(0)
  • 2021-01-29 13:11

    Perl supports lots of assignment operators. ||= is just a logical or (complete with shortcircuit,) assignment.

    So essentially what you're looking at is:

    if ($s->{_l}) {
      $my_link = $my_link || DownloadF($file,'l');
    }
    

    So if $my_link evaluates to some true value then $my_link will be assigned to itself (a no-op essentially), otherwise the result of DownloadF is assigned.

    Other assignment operators supported by perl:

     **= += *= &= <<= &&=
    -= /= |= >>= ||=
    .= %= ^= //=
    x=
    
    0 讨论(0)
  • 2021-01-29 13:16

    If $my_link is false (empty string, 0 or undef) store DownloadF($file,'l') into $my_link

    This construct has always had problems when used to assign a default value (what if you want $my_link to be zero)

    0 讨论(0)
提交回复
热议问题