in reply to scope of an autovivified variable?
used to be the idiom for achieving a state variable, that is, one that lived on from one invocation of a subroutine or block to another. it usually leads to more trouble than benefit, and anyway, since 5.10 there is the state keyword.
A simple way to achieve the result you want is to reverse the order of alternatives for @headerElements. Instead of handling the exception of $headerStr not having a value, why not assign @headerElements a deafult value, and then possibly override that with values derived from $headerStr?
my @headerElements = ( 'value 1', 'value 2', 'value 3' ); @headerElements = split /\s+/, $headerStr if $headerStr;
Another way is to preserve the order you had, but use a ternary operator ... an inline if-block:
my @headerElements = ( $headerStr ? split /\s+/, $headerStr : ( 'value 1', 'value 2', 'value 3' ) );
You could also do it using a logical-or test operator to detect whether the result of the split is a true or false value. This could result in complications if the left value is valid but logically false, for example, a zero or an empty string. But in this case it seems safe enough. Note that you have to parenthesize the arguments to split(), to specify the end of the arg list.
my @headerElements = split( /\s+/, $headerStr ) || ( 'value 1', 'value + 2', 'value 3' );
As Occam said: Entia non sunt multiplicanda praeter necessitatem.
|
---|