reference - Dereferencing Conditionally in Perl -


i have scalar may or may not reference array. if reference array, dereference , iterate on it. if not, treat one-element array , iterate on that.

my $result = my_complicated_expression; $value (ref($result) eq 'array' ? @$result : ($result)) {     # work $value } 

currently, have above code, works fine feels clunky , not perlish. there more concise way express idea of dereferencing value fallback behavior if value not expect?

being perl, there's going several answers 'right' 1 being matter of taste - imho, acceptable shortening involves relying on fact the ref function returns empty string if expression given scalar. means don't need eq 'array' if know there 2 possibilities (ie, scalar value , array ref).

secondly, can iterate on single scalar value (producing 1 iteration, obviously), don't have put $result in parentheses in "scalar" case.

putting these 2 small simplifications togeather gives;

use v5.12;  $result1 = "hello world"; $result2 = [ "hello" , "world" ];  $result ($result1, $result2) {     $value ( ref $result ? @$result : $result) {         $value ;     } } 

which produces;

hello world hello world 

there's 'fancier' things can do, seems reasonable compromise between being terse , readable. of course, ymmv.


Comments

Popular posts from this blog

scala - 'wrong top statement declaration' when using slick in IntelliJ -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

PySide and Qt Properties: Connecting signals from Python to QML -