develooper Front page | perl.beginners | Postings from May 2008

Re: one liner for for and if

Thread Previous | Thread Next
From:
Richard Lee
Date:
May 8, 2008 20:47
Subject:
Re: one liner for for and if
Rob Dixon wrote:
> Richard Lee wrote:
>   
>> #!/usr/bin/perl
>>
>> use warnings;
>> use strict;
>>
>> my @array = qw/one two three four/;
>>
>> print "$_\n" for @array last if "$_" eq q/three/;
>>
>>
>> [root@server tmp]# ./!$
>> ././././testthis2.pl
>> syntax error at ././././testthis2.pl line 8, near "@array last "
>> Execution of ././././testthis2.pl aborted due to compilation errors.
>>
>> Can someone fix my last statement on this program?
>>
>> I thought maybe this will work   but guess not... is there no easy way 
>> to do this?
>>
>> I don't want to do
>>
>> for (@array) {
>>      if .......
>>      }
>> }
>>
>>
>> just trying to see what the correct format is that for one liner that I 
>> am trying
>>     
>
> And you want to write it in one line why?
>
> print "$_\n" for grep /one/ .. /three/, @array;
>
> But there's nothing wrong with
>
> foreach (@array) {
>   print "$_\n";
>   last if /three/;
> }
>
> Rob
>   
#!/usr/bin/perl

use warnings;
use strict;

my @array = qw/one two three four/;

print "$_\n" for grep /three/, @array;

[root@server tmp]# !$
./test5.pl
three

this works well. However, that goes through entire array.. right?
So there is no true way to squeeze in the ' last ' .. ?

main reason is to see if it's doable(I like some of perl's idioms) and 
whether it is possible
The other reason is because I have a big array which I have to look in 
by 3 different steps
and I wanted to avoid 3 foreach loop in a row which key depends on 
preceding code and wanted to just go
---- simplied version----

my $something = $_ for @array last if "$_" eq q/three/;
my $something1 = $_ for @array last if "$_" eq q/$something/;
my $something2 = $_ for @array last if "$_" eq q/$something1/;

Anyway, I will try your code and report back.

thank you. 



Thread Previous | Thread Next


Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About