On Tue, Nov 25, 2008 at 1:03 PM, Ludwig Isaac Lim <[EMAIL PROTECTED]>wrote:

>
> Hi:
>
>  Is there a better way of rewriting the following perl statement?
>  (method 1)
>  @arr = split /\s+/, $str, $num_elem;
>
>  die("Should have $num_elem element") if ( (scalar @arr) != $some_number);


You may remove "scalar". "!=" operates only on scalar values, so the named
array above will be evaluated in scalar context even without "scalar".


>
>  $var1 = @arr[0];
>  $var2 = @arr[1];


@array[index] is wrong. The correct sigil for scalar values is "$",
even when the scalar is part of an array or hash. That was changed in
Perl 6 though, because many programmers get confused by that. :-)

 ...
>  ...
>  $varn  [EMAIL PROTECTED]<number>];
>
>  (method 2)
>
>   ($var1,$var2,$var3) = split /\s+/,@arr,3;
>

Passing an array as the second argument to split() and  expecting split()
to return a list is wrong. @arr will be evaluated in scalar context. Thus,
what will be passed to split() is the length of @arr.


>  But using method2 2, it seems the only way to check if 3 elements are
> returned by split is have
> something like this (I maybe wrong):
>
>   if (!(defined($var3))) {
>      die("less than 3 elements returned");
>   }
>
>
>   Any better way of combining the brevity of method 2 and the error
> checking of method 1?
>


Try
    @array = split(...);
    die if @array != $required_num_of_elts;
    ($var1, $var2, ...) = @array;

HTH
_________________________________________________
Philippine Linux Users' Group (PLUG) Mailing List
http://lists.linux.org.ph/mailman/listinfo/plug
Searchable Archives: http://archives.free.net.ph

Reply via email to