Prev: FAQ 5.25 How do I randomly update a binary file?
Next: Posting Guidelines for comp.lang.perl.misc ($Revision: 1.9 $)
From: David Bouman on 16 Jul 2010 06:01 On Jul 16, 3:27 am, Peng Yu <pengyu...(a)gmail.com> wrote: > I use the following command to OR the values in an array. I'm > wondering what is the best way to do so. A function similar to > 'accumulate' in mit-scheme or C++, may be helpful. But I don't find it > in perl. What about using a grep in scalar context? -- David.
From: Ben Morrow on 16 Jul 2010 12:53 Quoth Peng Yu <pengyu.ut(a)gmail.com>: > On Jul 15, 9:12�pm, Ben Morrow <b...(a)morrow.me.uk> wrote: > > > > The usual term for this operation is 'reduce'; you can find it in > > List::Util. Note that you need to explicitly provide an initial value: > > > > � � use List::Util qw/reduce/; > > > > � � my $result = reduce { $a || $b } 0, @array; > > > > In this case you could also use 'first': > > > > � � use List::Util qw/first/; > > > > � � my $result = first { $_ } 0, @array; > > #!/usr/bin/env perl > > use strict; > use warnings; > use List::Util; > > my @array=1..10; > my $result=List::Util::reduce { $a + $b } @array; > print $result, "\n"; > ########## > > I got the following warnings for the above problem. But the code from > the manual works. I'm wondering what is wrong in the above code? > > Name "main::b" used only once: possible typo at ./main.pl line 8. > Name "main::a" used only once: possible typo at ./main.pl line 8. This appears to be a bug in List::Util (I'll report it once I've verified this). The workaround, as you have discovered, is to mention $a and $b more than once in your program. Something entirely trivial like $a, $b; # work around 'used only once' warning will do. Ben
From: sln on 16 Jul 2010 14:09
On Thu, 15 Jul 2010 18:27:06 -0700 (PDT), Peng Yu <pengyu.ut(a)gmail.com> wrote: >Hi, > >I use the following command to OR the values in an array. I'm >wondering what is the best way to do so. A function similar to >'accumulate' in mit-scheme or C++, may be helpful. But I don't find it >in perl. > >my @array=(0,0,1); >my $result=0; >map { $result = $result || $_} @array; >print $result, "\n"; > >Regards, >Peng I'm just wondering which would be faster: $result ||= $_ and last for ( @array ); or $result |= $_ and last for ( @array ); -sln |