Re: What are these numbers (gmtime, slice)

2019-07-08 Thread Uri Guttman

On 7/8/19 4:00 PM, Mike Small wrote:

Uri Guttman  writes:


On 7/4/19 2:41 PM, Mike Small wrote:

A co-worker was trying to take some of the elements from gmtime's return
value. He did something like the following:

$ perl -E'$,="\t";say gmtime[1..5]'

that is calling gmtime with the argument of [1..5] which is an
arrayref. so the arg to gmtime is some large address number. it is
then parsed as the timestamp and broken out. garbage in, garbage out!

Thanks Uri! That makes perfect sense now that I see it explained.

that is one reason a rule i use is to always (mostly!) use () for the 
args list to builtins. it eliminates funny arg parsing and also shows to 
the reader there is a function call with no args. it would have caught 
the error as:


    gmtime()[1..5]

should be a syntax error (didn't check).

also a better way to slice out gmtime is to assign it to an list of 
scalars or an array slice (untested):


    (undef, @gmt_parts[1..5) ) = gmtime() ;

and you can pass the list from gmtime directly to strftime (in POSIX) to 
get a formatted date.


and in scalar context, you get a formatted date too. slicing into gmtime 
isn't needed that often.


all the notes above cover localtime as well. gmtime is the basis for 
localtime and the only difference is dealing with the local timezone and 
its offset from GMT (same as UTC).


remember, write your code as if the maintainer is a homicidal maniac who 
knows where you live!!


uri

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: What are these numbers (gmtime, slice)

2019-07-08 Thread Mike Small
Uri Guttman  writes:

> On 7/4/19 2:41 PM, Mike Small wrote:
>> A co-worker was trying to take some of the elements from gmtime's return
>> value. He did something like the following:
>>
>> $ perl -E'$,="\t";say gmtime[1..5]'
>
> that is calling gmtime with the argument of [1..5] which is an
> arrayref. so the arg to gmtime is some large address number. it is
> then parsed as the timestamp and broken out. garbage in, garbage out!

Thanks Uri! That makes perfect sense now that I see it explained.

-- 
Mike Small
sma...@sdf.org

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: What are these numbers (gmtime, slice)

2019-07-07 Thread Uri Guttman

On 7/4/19 2:41 PM, Mike Small wrote:

A co-worker was trying to take some of the elements from gmtime's return
value. He did something like the following:

$ perl -E'$,="\t";say gmtime[1..5]'


that is calling gmtime with the argument of [1..5] which is an arrayref. 
so the arg to gmtime is some large address number. it is then parsed as 
the timestamp and broken out. garbage in, garbage out!

8   32  12  31  7   2999416 1   243 0

I suggested he try something like this instead...

$ perl -E'$,="\t";say ((gmtime)[1..5])'
36  18  4   6   119
here gmtime is called with no args as it is in parens. so it uses the 
value of time() which is what he wanted.



... and that was what he wanted, but it didn't matter because he
re-rewrote his code to use strftime, which we both thought was more
readable.  But still, what are those numbers in the first example?
Neither of us can figure where they come from. The parens must be a
clue, but all I could think was gmtime was interpreted as an array
reference, but thinking that didn't get me anywhere that made sense to
me.
it is an array ref. but it is used as the epoch time and it is wacky for 
that.


uri

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




What are these numbers (gmtime, slice)

2019-07-07 Thread Mike Small
A co-worker was trying to take some of the elements from gmtime's return
value. He did something like the following:

$ perl -E'$,="\t";say gmtime[1..5]'
8   32  12  31  7   2999416 1   243 0

I suggested he try something like this instead...

$ perl -E'$,="\t";say ((gmtime)[1..5])' 
36  18  4   6   119

... and that was what he wanted, but it didn't matter because he
re-rewrote his code to use strftime, which we both thought was more
readable.  But still, what are those numbers in the first example?
Neither of us can figure where they come from. The parens must be a
clue, but all I could think was gmtime was interpreted as an array
reference, but thinking that didn't get me anywhere that made sense to
me.

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Fwd: slice of an arrayref

2010-10-29 Thread shawn wilson
i am having an issue here, i think the bulk of it revolves around this;
print join(',', @uword{ $seen{ $key }[ 1 ] }[ 1 .. $#{ @uword{
$seen( $key ) } } ] );

however, given how that looks, i'm thinking i've got others.

so, pretty much, what i do is go through each line and take out the words
and take out the duplicate words. i take the hash of those words and put the
full text from the lines they came from and push it onto the array reference
to that hashref. i then go and search a database for each word and take out
the duplicates of the results (keeping the search terms with the results -
though there's a minor logic issue with this i think - if two searches bring
up the same text, i'll just know about the first). the result string and the
word that was searched to find the string are stored to the same type of
array reference to a hashref. that all works fine (exept my many to many
problem i noted above). my issue is how to print out a slice of an arrayref
of a hashref?

my underlying problem (i think) is that there has got to be a better way?

i've got half a mind to create a temp table in the db to do this, but that
doesn't seem like my 'better way' either.

thanks

#!/usr/bin/perl

# WHAT #
# What names return per search
##

use strict;
use warnings;
use DBI;

my $searcher = owner.manager, owner.owner, owner.manown;

my $dbh = DBI-connect('DBI:mysql:db;host=localhost',
'user', 'word')
or die Database connection: $!;

open( FILE,  $ARGV[0] );

my %uword = ();
my %seen = ();
my $count = 0;
my @data;
my $key;
my $i = 0;

while ( FILE ) {

my $line = $_;

chomp ($line);
my @word = split / /, $line;


$count = 0;
while ( $word[ $count ] ) {
$word[ $count ] =~ tr/^[\-a-zA-Z]//;
$word[ $count ] =~ s/\'/\\\'/g;
$count++;
}

foreach my $string ( @word ) {
if ( $uword{ $string }[ 0 ] == 1 ) {
push @{ $uword{ $string } }, $line;
next;
}
$uword{ $string }[ 0 ] = 1;
push @{ $uword{ $string } }, $line;
}
}


for my $key ( keys %uword ) {

my ( $number, $owner, $manown, $manager );

my $select =qq/SELECT $searcher /;
my $from =  qq/FROM owner, spd /;
my $where = qq/WHERE MATCH( $searcher ) AGAINST('+$key'
IN BOOLEAN MODE) /;
my $join =  qq/AND owner.num = spd.num/;

my $query = $select . $from . $where . $join;

print SQL: $query\n;
my $sth = $dbh-prepare( $query );
$sth-execute;

$sth-bind_columns( \$manager, \$owner, \$manown );

while ( $sth-fetch ) {

if ( defined( $owner ) ) {
$data[$count] = $owner;
$count++;
}
if ( defined( $manown ) ) {
$data[$count] = $manown;
$count++;
}
if ( defined( $manager ) ) {
$data[$count] = $manager;
$count++
}
}

# @data holds full names of data.

foreach my $string ( @data ) {   # dedupe data and sanity check.
next if !defined ($string);   # should never be true.
next if $seen{ $string }[ 0 ] == 1; # check %seen hash /
array for dupe
$seen{ $string }[ 0 ] = 1;# define hash of array and
assign check to it.
$seen{ $string }[ 1 ] = $key; # add word from line to hash
for reference.
}
}

$dbh-disconnect;

# $key - (below) is the deduped sql string
# $seen { $key }[ 1 ]  - is the word searched in sql
# $uword { '$seen{ $key }[ 1 ]' }  - should be the line(s) of test the
search string came from

for my $key ( keys %seen ) {

print $seen{ $key }[ 1 ], $key,;
print join(',', @uword{ $seen{ $key }[ 1 ] }[ 1 .. $#{ @uword{
$seen( $key ) } } ] );
print \n;
}


Slice?

2009-03-16 Thread R. Hicks

$template-param(
  RESULTS = $self-dbh-selectall_arrayref('
SELECT age, day FROM table WHERE id = ?',
{ Slice = {} },
$self-session-param('cell')-{'sid'} )
);


I saw that code and while I do database stuff I was wondering what that 
Slice = {} does?


Thanks,

Robert

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: Slice?

2009-03-16 Thread Jim Gibson
On 3/16/09 Mon  Mar 16, 2009  3:05 PM, R. Hicks sigz...@gmail.com
scribbled:

 $template-param(
RESULTS = $self-dbh-selectall_arrayref('
  SELECT age, day FROM table WHERE id = ?',
  { Slice = {} },
  $self-session-param('cell')-{'sid'} )
 );
 
 
 I saw that code and while I do database stuff I was wondering what that
 Slice = {} does?

Check the documentation for the DBI module, which you can get from 'perldoc
DBI' at a command-line shell (or
http://search.cpan.org/~timb/DBI-1.607/DBI.pm in a browser),
 in particular the description for the selectall_arrayref method, which has
as its third form the following:

  $ary_ref = $dbh-selectall_arrayref($statement, \%attr, @bind_values);

If the \%attr argument contains {Slice={}}, then the values will be
returned as a hash. From the documentation:

  my $emps = $dbh-selectall_arrayref(
  SELECT ename FROM emp ORDER BY ename,
  { Slice = {} }
  );
  foreach my $emp ( @$emps ) {
  print Employee: $emp-{ename}\n;
  } 



-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: Assigning an array to a dereferenced hash slice - syntax!

2009-03-14 Thread Chas. Owens
On Sat, Mar 14, 2009 at 01:06, Chap Harrison c...@pobox.com wrote:

 On Mar 13, 2009, at 7:52 AM, Jenda Krynicky wrote:

 That's prettymuch it, except that it's not an array of aliases, but
 LIST of aliases. The difference is subtle, but important.
 See http://perldoc.perl.org/perlfaq4.html#What-is-the-difference-
 between-a-list-and-an-array%3f and
 http://www.perlmonks.org/?node_id=130861

 Thanks - I've read the FAQ several times in the past without really getting
 it, but the perlmonks thread looks promising.  It IS subtle, all right.  :-/
snip

The eureka moment for me was when I realized that lists are a data
type (like number or string) and arrays and hashes are containers that
hold that data type.  Once you realize that it is easy to see why they
have different behaviours.


-- 
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: Assigning an array to a dereferenced hash slice - syntax!

2009-03-13 Thread Jenda Krynicky
From:   Chap Harrison c...@pobox.com
 Let me break this expression down according to my current understanding.
 
 @{$hash{adams...@keys} = @values;
 
 parses as follows:
 
 adams  : short for 'adams', a string literal, being used as a hash key
 $hash{adams} : the value in the hash associated with 'adams', a scalar  
 (always), and a ref to a hash in this case
 {$hash{adams}} : extra braces, used to force correct binding (?)  
 with surrounding context, I expect.
 {$hash{adams...@keys} : the hashref is dereferenced, and a set of keys  
 (provided by an array) is looked up in the hash, resulting in a set of  
 values; or, more precisely, *aliases* of values.
 @{$hash{adams...@keys} : an array of aliases of the hash values  
 associated with the keys supplied in @keys.
 @{$hash{adams...@keys} = @values : behaves much like...
 
 ( $hash{adams}{a}, $hash{adams}{ar}, $hash{adams}{af}, $hash{adams} 
 {aw} ) = ( 1, 19, 13, 11 )


That's prettymuch it, except that it's not an array of aliases, but 
LIST of aliases. The difference is subtle, but important.
See http://perldoc.perl.org/perlfaq4.html#What-is-the-difference-
between-a-list-and-an-array%3f and 
http://www.perlmonks.org/?node_id=130861

And it doesn't really make sense to add only the {...@keys} without the 
@. You have to consider them both at the same time, because the sigil 
you use affects how is the @keys evaluated!

See

%hash = (a = 999, b = 888, c = 777, d = 666, 3 = 123456);
@keys = ('a','b','c');

print $ha...@keys},\n;
print @ha...@keys},\n;

$href = \%hash;

print ${$hre...@keys},\n;
print @{$hre...@keys},\n;


HTH, Jenda
= je...@krynicky.cz === http://Jenda.Krynicky.cz =
When it comes to wine, women and song, wizards are allowed 
to get drunk and croon as much as they like.
-- Terry Pratchett in Sourcery


-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: Assigning an array to a dereferenced hash slice - syntax!

2009-03-13 Thread Chap Harrison


On Mar 13, 2009, at 7:52 AM, Jenda Krynicky wrote:


That's prettymuch it, except that it's not an array of aliases, but
LIST of aliases. The difference is subtle, but important.
See http://perldoc.perl.org/perlfaq4.html#What-is-the-difference-
between-a-list-and-an-array%3f and
http://www.perlmonks.org/?node_id=130861


Thanks - I've read the FAQ several times in the past without really  
getting it, but the perlmonks thread looks promising.  It IS subtle,  
all right.  :-/


And it doesn't really make sense to add only the {...@keys} without the
@. You have to consider them both at the same time, because the sigil
you use affects how is the @keys evaluated!


Yes, I see your point.

That exercise helped to clarify it a bit more.  Thanks to everyone for  
helping me!


Chap


--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: Assigning an array to a dereferenced hash slice - syntax!

2009-03-12 Thread Chap Harrison


On Mar 12, 2009, at 12:52 AM, Chas. Owens wrote:


On Thu, Mar 12, 2009 at 01:27, Chap Harrison c...@pobox.com wrote:


It's still not intuitive to me why we FIRST convert the hash to  
an array,
and THEN ask for keys - keys being hash-ish, rather than array-ish  
sorts of
things.  (I've said that badly.)  What exactly are the elements of  
the array

@{$hash{adams...@keys} ?

snip

It isn't really becoming an array.  A better way to think of it is
that $ means we expect one value back from the data structure:


Let me break this expression down according to my current understanding.

@{$hash{adams...@keys} = @values;

parses as follows:

adams  : short for 'adams', a string literal, being used as a hash key
$hash{adams} : the value in the hash associated with 'adams', a scalar  
(always), and a ref to a hash in this case
{$hash{adams}} : extra braces, used to force correct binding (?)  
with surrounding context, I expect.
{$hash{adams...@keys} : the hashref is dereferenced, and a set of keys  
(provided by an array) is looked up in the hash, resulting in a set of  
values; or, more precisely, *aliases* of values.
@{$hash{adams...@keys} : an array of aliases of the hash values  
associated with the keys supplied in @keys.

@{$hash{adams...@keys} = @values : behaves much like...

( $hash{adams}{a}, $hash{adams}{ar}, $hash{adams}{af}, $hash{adams} 
{aw} ) = ( 1, 19, 13, 11 )



So that's my own badly-described understanding of how that expression  
does what it does.  I'd greatly appreciate any corrections.


--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Assigning an array to a dereferenced hash slice - syntax!

2009-03-11 Thread Chap Harrison

Hello,
I have a hash of hashes, and I'm trying to bulk-assign some key/value  
pairs to the referenced hash, using a technique I read on the  
perlmonks list (hash slices, see link below).  I've never been good at  
working out syntax where complex data structures are concerned, and  
this eludes me completely.  Could someone please help me with the  
syntax of the assignment, and retrieval of key/value pairs?


Thanks - I appreciate it!
Chap
*
#!/usr/bin/perl -d

use strict;
use warnings;

my %schoolprops;

#  +  
-

#  |  %schoolprops - a hash of references to hashes
#  |
#  |  key  valuehash
#  | ---
---

#  |  Adams--  {a = 1, ar = 19, af = 13, aw = 11}
#  |  Baker--  {b = 2, bq = 20}
#  |  Charlie  --  {c = 3, cc = 33, cu = 38}
#  +  
-


$schoolprops{Adams} = \{};  # map 'Adams' to a ref to an empty hash

my $hashref = $schoolprops{Adams}; # create a ref to a hash.

my @keys = ( 'a', 'ar', 'af', 'aw' );
my @values = ( 1, 19, 13, 11);

#
# The following is trying to assign an array to a hash slice.
# (courtesy http://www.perlmonks.org/?node_id=4402, who did a simpler
# version that did not involve references.)
#
@{{$hashref}-{...@keys}} = @values;# don't know if this is right

while (my ($k, $v) = each %{$hashref}) { # this is just one of many  
things

print $k = $v\n; # I've tried; this one fails at 
runtime.
}
#EOF
*


--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: Assigning an array to a dereferenced hash slice - syntax!

2009-03-11 Thread Chas. Owens
On Thu, Mar 12, 2009 at 00:19, Chap Harrison c...@pobox.com wrote:
 Hello,
 I have a hash of hashes, and I'm trying to bulk-assign some key/value pairs
 to the referenced hash, using a technique I read on the perlmonks list (hash
 slices, see link below).  I've never been good at working out syntax where
 complex data structures are concerned, and this eludes me completely.  Could
 someone please help me with the syntax of the assignment, and retrieval of
 key/value pairs?

 Thanks - I appreciate it!
 Chap
 *
 #!/usr/bin/perl -d

 use strict;
 use warnings;

 my %schoolprops;

 #  +
 -
 #  |  %schoolprops - a hash of references to hashes
 #  |
 #  |  key          value    hash
 #  | ---
 ---
 #  |  Adams        --      {a = 1, ar = 19, af = 13, aw = 11}
 #  |  Baker        --      {b = 2, bq = 20}
 #  |  Charlie      --      {c = 3, cc = 33, cu = 38}
 #  +
 -

 $schoolprops{Adams} = \{};      # map 'Adams' to a ref to an empty hash

 my $hashref = $schoolprops{Adams}; # create a ref to a hash.

 my @keys = ( 'a', 'ar', 'af', 'aw' );
 my @values = ( 1, 19, 13, 11);

 #
 # The following is trying to assign an array to a hash slice.
 # (courtesy http://www.perlmonks.org/?node_id=4402, who did a simpler
 # version that did not involve references.)
 #
 @{{$hashref}-{...@keys}} = @values;        # don't know if this is right

 while (my ($k, $v) = each %{$hashref}) { # this is just one of many things
    print $k = $v\n;                  # I've tried; this one fails at
 runtime.
 }
 #EOF
 *

Dereference the hashref as an arrayref then ask for the keys:

#!/usr/bin/perl

use strict;
use warnings;

my %hash = ( adams = {} );

my @keys   = qw/a ar af aw/;
my @values = (1, 19, 13, 11);

@{$hash{adams...@keys} = @values;

use Data::Dumper;

print Dumper \%hash;



-- 
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: Assigning an array to a dereferenced hash slice - syntax!

2009-03-11 Thread Chap Harrison

On Mar 11, 2009, at 11:51 PM, Chas. Owens wrote:


Dereference the hashref as an arrayref then ask for the keys:

#!/usr/bin/perl

use strict;
use warnings;

my %hash = ( adams = {} );

my @keys   = qw/a ar af aw/;
my @values = (1, 19, 13, 11);

@{$hash{adams...@keys} = @values;

use Data::Dumper;

print Dumper \%hash;



Thank you for both a solution and several other useful tips as well!

It's still not intuitive to me why we FIRST convert the hash to an  
array, and THEN ask for keys - keys being hash-ish, rather than array- 
ish sorts of things.  (I've said that badly.)  What exactly are the  
elements of the array @{$hash{adams...@keys} ?


Thanks,
Chap.

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: Assigning an array to a dereferenced hash slice - syntax!

2009-03-11 Thread John W. Krahn

Chap Harrison wrote:

Hello,


Hello,

I have a hash of hashes, and I'm trying to bulk-assign some key/value 
pairs to the referenced hash, using a technique I read on the perlmonks 
list (hash slices, see link below).  I've never been good at working out 
syntax where complex data structures are concerned, and this eludes me 
completely.  Could someone please help me with the syntax of the 
assignment, and retrieval of key/value pairs?


Thanks - I appreciate it!
Chap
*
#!/usr/bin/perl -d

use strict;
use warnings;

my %schoolprops;

#  + 
-

#  |  %schoolprops - a hash of references to hashes
#  |
#  |  key  valuehash
#  | ---   
---

#  |  Adams--  {a = 1, ar = 19, af = 13, aw = 11}
#  |  Baker--  {b = 2, bq = 20}
#  |  Charlie  --  {c = 3, cc = 33, cu = 38}
#  + 
-


$schoolprops{Adams} = \{};# map 'Adams' to a ref to an empty hash


{} *is* a reference to an empty hash, \{} is a reference to a reference 
to an empty hash.




my $hashref = $schoolprops{Adams}; # create a ref to a hash.


It doesn't create it, it just copies it.



my @keys = ( 'a', 'ar', 'af', 'aw' );
my @values = ( 1, 19, 13, 11);

#
# The following is trying to assign an array to a hash slice.
# (courtesy http://www.perlmonks.org/?node_id=4402, who did a simpler
# version that did not involve references.)
#
@{{$hashref}-{...@keys}} = @values;# don't know if this is right


If you change = \{} to = {} then:

@{ $hashref }{ @keys } = @values;

Otherwise it won't work.



while (my ($k, $v) = each %{$hashref}) { # this is just one of many things
print $k = $v\n; # I've tried; this one fails at 
runtime.

}



John
--
Those people who think they know everything are a great
annoyance to those of us who do.-- Isaac Asimov

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: Assigning an array to a dereferenced hash slice - syntax!

2009-03-11 Thread John W. Krahn

Chap Harrison wrote:

On Mar 11, 2009, at 11:51 PM, Chas. Owens wrote:


Dereference the hashref as an arrayref then ask for the keys:

#!/usr/bin/perl

use strict;
use warnings;

my %hash = ( adams = {} );

my @keys   = qw/a ar af aw/;
my @values = (1, 19, 13, 11);

@{$hash{adams...@keys} = @values;

use Data::Dumper;

print Dumper \%hash;



Thank you for both a solution and several other useful tips as well!

It's still not intuitive to me why we FIRST convert the hash to an 
array, and THEN ask for keys - keys being hash-ish, rather than 
array-ish sorts of things.  (I've said that badly.)  What exactly are 
the elements of the array @{$hash{adams...@keys} ?


@{$hash{adams...@keys} is *not* an array, it is a hash slice.



John
--
Those people who think they know everything are a great
annoyance to those of us who do.-- Isaac Asimov

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: Assigning an array to a dereferenced hash slice - syntax!

2009-03-11 Thread Chas. Owens
On Thu, Mar 12, 2009 at 01:27, Chap Harrison c...@pobox.com wrote:
 On Mar 11, 2009, at 11:51 PM, Chas. Owens wrote:

 Dereference the hashref as an arrayref then ask for the keys:

 #!/usr/bin/perl

 use strict;
 use warnings;

 my %hash = ( adams = {} );

 my @keys   = qw/a ar af aw/;
 my @values = (1, 19, 13, 11);

 @{$hash{adams...@keys} = @values;

 use Data::Dumper;

 print Dumper \%hash;


 Thank you for both a solution and several other useful tips as well!

 It's still not intuitive to me why we FIRST convert the hash to an array,
 and THEN ask for keys - keys being hash-ish, rather than array-ish sorts of
 things.  (I've said that badly.)  What exactly are the elements of the array
 @{$hash{adams...@keys} ?
snip

It isn't really becoming an array.  A better way to think of it is
that $ means we expect one value back from the data structure:

my $scalar = $array[0];
my $scalar = $hash{foo};

and @ means we expect to get many values back from the data structure

my @result = @array[0 .. 5];
my @result = @hash{qw/foo bar baz/};

of course, you have to look at the context to determine what happens:

my $length = @array;





-- 
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




hash slice??

2008-11-10 Thread Travis Thornhill
Is there such a thing?
 
I'm trying to take a HoH and make a reference to a sub-part of the hash.
 
This doesn't work:
 
my %sub_hash = $main_hash{'sub_hash'};
 
I get the following error:
Reference found where even-sized list expected at ./my_buggy_program line 30.
 
Any quick tips on how to reference and assign this sub-hash?
 
Thanks,
- Travis


  

Re: hash slice??

2008-11-10 Thread Chas. Owens
On Mon, Nov 10, 2008 at 09:52, Travis Thornhill
[EMAIL PROTECTED] wrote:
 Is there such a thing?

 I'm trying to take a HoH and make a reference to a sub-part of the hash.

 This doesn't work:

 my %sub_hash = $main_hash{'sub_hash'};

 I get the following error:
 Reference found where even-sized list expected at ./my_buggy_program line 30.

 Any quick tips on how to reference and assign this sub-hash?
snip

#!/usr/bin/perl

use strict;
use warnings;

use Data::Dumper;

my %name_to_num = (
one   = 1,
two   = 2,
three = 3,
four  = 4,
five  = 5,
six   = 6
);

#get keys whose values are odd
my @keys = grep { $name_to_num{$_} % 2 } keys %name_to_num;

#make a hash of the odd keys and values with a hash slice
my %odd_name_to_num;
@[EMAIL PROTECTED] = @[EMAIL PROTECTED];

print Dumper \%name_to_num, \%odd_name_to_num;


-- 
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: hash slice??

2008-11-10 Thread Rob Coops
On Mon, Nov 10, 2008 at 3:52 PM, Travis Thornhill [EMAIL PROTECTED]
 wrote:

 Is there such a thing?

 I'm trying to take a HoH and make a reference to a sub-part of the hash.

 This doesn't work:

 my %sub_hash = $main_hash{'sub_hash'};

 I get the following error:
 Reference found where even-sized list expected at ./my_buggy_program line
 30.

 Any quick tips on how to reference and assign this sub-hash?

 Thanks,
 - Travis





Hi Travis,

The problem you are facing is that $main_hash{'sub_hash'} does not return a
hash at all but a reference. Which is exactly what perl is telling you. You
can simply tell perl that it should dereference the reference to a hash, you
could do that like this:

#!/usr/bin/perl

use warnings;
use strict;
use Data::Dumper;

my %hash = ( 1 = 'one',
 2 = 'two',
 3 = { 3.1 = 'three point one',
3.2 = 'three point two' },
 4 = 'four' );
my %hash_slice = %{$hash{3}};
print Dumper %hash_slice;
Reagrds,

Rob


Re: hash slice??

2008-11-10 Thread John W. Krahn

Travis Thornhill wrote:

Is there such a thing?


Yes there is.


I'm trying to take a HoH and make a reference to a sub-part of the hash.

This doesn't work:

my %sub_hash = $main_hash{'sub_hash'};

I get the following error:
Reference found where even-sized list expected at ./my_buggy_program line 30.

Any quick tips on how to reference and assign this sub-hash?


my %sub_hash;

@sub_hash{ 'sub_hash' } = @main_hash{ 'sub_hash' };


John
--
Perl isn't a toolbox, but a small machine shop where you
can special-order certain sorts of tools at low cost and
in short order.-- Larry Wall

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: hash slice??

2008-11-10 Thread Rob Dixon
Travis Thornhill wrote:

 Is there such a thing?
  
 I'm trying to take a HoH and make a reference to a sub-part of the hash.
  
 This doesn't work:
  
 my %sub_hash = $main_hash{'sub_hash'};
  
 I get the following error:
 Reference found where even-sized list expected at ./my_buggy_program line 30.
  
 Any quick tips on how to reference and assign this sub-hash?

There is certainly such a thing as a hash slice, but I think it is probably not
what you want here. A slice will let you extract multiple values from the hash
simultaneously, something like

  my @subhashes = @main_hash{'key1', 'key2', 'key3'};

and it doesn't look to me like that's what you're trying to achieve.

If you have a hash of hashes then $main_hash{'sub_hash'} is already a reference,
as the error message has told you, so you should write

  my $subhash_ref = $main_hash{'sub_hash'};

after which you can access the subsidiary hash with constructs like

  foreach my $key (keys %$subhash_ref) {
printf %s = %s\n, $key, $subhash_ref-{$key};
  }

HTH,

Rob

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Issue with references and array slice with one member !

2008-10-31 Thread Amit Saxena
Hello all,

Recently I faced one scenario with references and array slice in perl.

I used following program to retrieve the rows from a table in Oracle using
Perl DBI.

As shown in the program, I did following steps to retrieve the rows :-


   - used fetchall_arrayref to get the array reference to the complete
   table
   - dereferenced the reference fetchall_arrayref and iterate one by one
   over each row $row in a foreach loop
   - further deferenced $row to get the columns one by one

Now here is the problem,

I used ${$row}[0], ${$row}[1] etc one by one to get all the columns for
a particular code. On one of the production code which I am working, they
have used @{$row}[0] , @{$row}[0] instead of earlier. The results for
both of them were same.

When I did a through debugging on this, I found that @{$row}[0] or
@{$row}[1] etc is taken as array slice by perl with only one member so it
returns the value of the column in scalar and not in list context. With
${$row}[0] or ${$row}[1] etc, the column value is returned in scaler
context.

I want to know whether it's appropriate to use @{$row}[0] , @{$row}[1]
instead of ${$row}[0], ${$row}[1] though both of them gives same result
?

# cat o1.pl
#!/usr/bin/perl
##!/u01/app/oracle/product/10.1.0/db_1/perl/bin/perl
# Example PERL DBI/DBD Oracle Example on Oracle 10g
use strict;
use warnings;
use DBI;
my $dbname = *;   ## DB Name from tnsnames.ora
my $user = *;
my $passwd = *;
 Connect to the database and return a database handle
my $dbh = DBI-connect(dbi:Oracle:${dbname}, $user, $passwd);
if($dbh){
print(Connected as user $user\n);
} else {
print(Failed to connect!\n);
exit;
}
 Prepare and Execute a SQL Statement Handle
my $sth = $dbh-prepare(SELECT owner,table_name,num_rows FROM all_tables);
# my $sth = $dbh-prepare(SELECT * FROM all_tables);
$sth-execute();
my $allTablesRow = $sth-fetchall_arrayref();
foreach my $row (@{$allTablesRow})
{
if (defined ${$row}[0])
{
print ${$row}[0];
}
else
{
print NULL;
}
if (defined ${$row}[1])
{
print ${$row}[1];
}
else
{
print NULL;
}
if (defined ${$row}[2])
{
print ${$row}[2];
}
else
{
print NULL;
}
print \n;
}
 Disconnect
#$dbh-disconnect;
You have mail in /var/spool/mail/root
#


Thanks  Regards,
Amit Saxena


Re: Issue with references and array slice with one member !

2008-10-31 Thread Chas. Owens
On Fri, Oct 31, 2008 at 05:46, Amit Saxena [EMAIL PROTECTED] wrote:
snip
 I used ${$row}[0], ${$row}[1] etc one by one to get all the columns for
 a particular code. On one of the production code which I am working, they
 have used @{$row}[0] , @{$row}[0] instead of earlier. The results for
 both of them were same.

 When I did a through debugging on this, I found that @{$row}[0] or
 @{$row}[1] etc is taken as array slice by perl with only one member so it
 returns the value of the column in scalar and not in list context. With
 ${$row}[0] or ${$row}[1] etc, the column value is returned in scaler
 context.

 I want to know whether it's appropriate to use @{$row}[0] , @{$row}[1]
 instead of ${$row}[0], ${$row}[1] though both of them gives same result
snip

${$row}[0] is better, but $row-[0] is best.

If you need ammunition to convince others then show them this code and
then run it on a fairly modern Perl interpreter.  Perl will throw a
warning like Scalar value @a[0] better written as $a[0] at z.pl line
8.  It is interesting a warning isn't thrown for references.  I shall
have to research that.

#!/usr/bin/perl

use strict;
use warnings;

my @a = qw/a b c/;

print @a[0], \n;

All of that said, @{$row}[0] has its uses:

@{$row}[0] = qw(a b c);

produces difference results from

$row-[0] = qw(a b c);

But it is probably better written as

$row-[0] = (qw(a b c))[0];

to avoid confusing people.

-- 
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: populating a hash slice from a filehandle

2008-06-23 Thread Jay Savage
On Fri, Jun 20, 2008 at 4:52 PM, Bryan R Harris
[EMAIL PROTECTED] wrote:

 Bryan R Harris wrote:

 John W. Krahn wrote:

 Bryan R Harris wrote:

 John W. Krahn wrote:

 The left hand side of the assignment determines context so the @l2r{...}
 part.

 That strikes me as odd...  When perl goes to populate @l2r{a,b}, it
 seems to me that it would go through this process:

 - I have a slice here, so I'll loop over the slice elements
 - The first is a, so I'll pull a scalar off the list and assign it to
 $l2r{a}
 - The second is b, so I'll pull another scalar off the list and assign 
 it
 to $l2r{b}
 - Remaining scalars in the list are discarded

 Correct, except for the loop part.

 Why would $l2r{a} here be considered list context?

 It isn't, unless it's written as ( $l2r{a} ), then it's a list with
 one element.

 So I still don't understand what about @l2r{a,b} makes it evaluate the
 first (FILE... in list context instead of scalar context.

 The '@' sigil at the front of the variable name says that it is either
 an array or a slice and so it forces list context on the right hand side
 of the assignment.

 I think it finally clicked!

 It makes more sense to me that (FILE,FILE) is kind of the same thing as
 saying (@a,@b).  In list context @a returns the array as a list, but in
 scalar context @a returns the number of elements.  Obviously (@a,@b) returns
 the union of the two lists, not two scalars.  FILE is treated the same
 way.


Bryan,

That isn't really as obvious as you think. There are probably
situations where (@a, @b) would be a list of scalars. I'll say it
again: the function of the parentheses in a particular situation
(grouping, precedence, capturing, list assignment) is assign *after*
context is determined. Context has to do with the result you are
asking for, not the data you are inputting. Just because you are
working with a list doesn't mean your expression will be evaluated in
list context. The important thing to keep sight of is that it is what
happens on the lefthand side of the equals sign that forces the
context, here, and there is nothing on the righthand side to
explicitly force a change.

You can think of this as an apples to apples issue. Lists can be
assigned to lists, and processed as lists. When you perform an
operation on a list, you aren't always iterating over the elements in
sequence. A list is a collection of scalars, true, but it's also a
fundamental data type in its own right. A slice is a type of list, so
Perl looks at the slice assignment and says I need a list. It then
evaluates the expression on the right with an eye toward making a
list. *Then* it worries about how the elements of the list on the
right will be affected by whatever has to happen to the list on the
left.

HTH,

-- j
--
This email and attachment(s): [ ] blogable; [ x ] ask first; [ ]
private and confidential

daggerquill [at] gmail [dot] com
http://www.tuaw.com http://www.downloadsquad.com http://www.engatiki.org

values of β will give rise to dom!


Re: populating a hash slice from a filehandle

2008-06-23 Thread Bryan R Harris

 From: Bryan R Harris [EMAIL PROTECTED]
 Bryan R Harris wrote:
 
 John W. Krahn wrote:
 
 Bryan R Harris wrote:
 
 John W. Krahn wrote:
 
 The left hand side of the assignment determines context so the @l2r{...}
 part.
 
 That strikes me as odd...  When perl goes to populate @l2r{a,b}, it
 seems to me that it would go through this process:
 
 - I have a slice here, so I'll loop over the slice elements
 - The first is a, so I'll pull a scalar off the list and assign it to
 $l2r{a}
 - The second is b, so I'll pull another scalar off the list and assign
 it
 to $l2r{b}
 - Remaining scalars in the list are discarded
 
 Correct, except for the loop part.
 
 Why would $l2r{a} here be considered list context?
 
 It isn't, unless it's written as ( $l2r{a} ), then it's a list with
 one element.
 
 So I still don't understand what about @l2r{a,b} makes it evaluate the
 first (FILE... in list context instead of scalar context.
 
 The '@' sigil at the front of the variable name says that it is either
 an array or a slice and so it forces list context on the right hand side
 of the assignment.
 
 I think it finally clicked!
 
 It makes more sense to me that (FILE,FILE) is kind of the same thing as
 saying (@a,@b).  In list context @a returns the array as a list, but in
 scalar context @a returns the number of elements.  Obviously (@a,@b) returns
 the union of the two lists, not two scalars.  FILE is treated the same
 way.
 
 Almost. It still depends on the left hand side. Try this:
 
 @a = (10,20,30);
 @b = (40,50,60);
 
 $s = (@a,@b);
 print $s\n;
 #versus
 ($s) = (@a,@b);
 print $s\n;
 
 
 In the first case the @a and @b are evaluated in scalar context. Even
 though they are enclosed in braces.

Dang!

But your example helped -- this one makes sense to me, at least:

perl -e '@a=(1,2,3);@b=(4,5,6,7);@l{1,2}=(@a,@b);print $l{1}\t$l{2}\n;'

Should I think of this as:  ($l{1}, $l{2}) = (@a,@b)
?

If so, then that makes a lot more sense to me.

Thanks for helping me along on this one...

- Bryan




-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: populating a hash slice from a filehandle

2008-06-23 Thread Jenda Krynicky
From:Bryan R Harris [EMAIL PROTECTED]
 Jenda wrote:
  From: Bryan R Harris [EMAIL PROTECTED]
  It makes more sense to me that (FILE,FILE) is kind of the same thing as
  saying (@a,@b).  In list context @a returns the array as a list, but in
  scalar context @a returns the number of elements.  Obviously (@a,@b) 
  returns
  the union of the two lists, not two scalars.  FILE is treated the same
  way.
  
  Almost. It still depends on the left hand side. Try this:
  
  @a = (10,20,30);
  @b = (40,50,60);
  
  $s = (@a,@b);
  print $s\n;
  #versus
  ($s) = (@a,@b);
  print $s\n;
  
  
  In the first case the @a and @b are evaluated in scalar context. Even
  though they are enclosed in braces.
 
 Dang!
 
 But your example helped -- this one makes sense to me, at least:
 
 perl -e '@a=(1,2,3);@b=(4,5,6,7);@l{1,2}=(@a,@b);print $l{1}\t$l{2}\n;'
 
 Should I think of this as:  ($l{1}, $l{2}) = (@a,@b)
 ?
 
 If so, then that makes a lot more sense to me.

Right. That's it. 
The fact that there is the same number of things in the braces on 
both sides of the equals might be a bit confusing at first, but it's 
irrelevant. Since in this case the equals provide a list context for 
the (@a,@b), the two arrays are flattened into one list. So 


($l{1}, $l{2}) = (@a,@b,@c);

or 

($l{1}, $l{2}, $l{4}) = (@a,@b);

would be just as OK. The commas are not matched, the elements of the 
two lists are. The list of specified elements of %l and the list of 
all elements of @a and @b.

Jenda
= [EMAIL PROTECTED] === http://Jenda.Krynicky.cz =
When it comes to wine, women and song, wizards are allowed 
to get drunk and croon as much as they like.
-- Terry Pratchett in Sourcery


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: populating a hash slice from a filehandle

2008-06-21 Thread Jenda Krynicky
From: Bryan R Harris [EMAIL PROTECTED]
  Bryan R Harris wrote:
  
  John W. Krahn wrote:
  
  Bryan R Harris wrote:
  
  John W. Krahn wrote:
  
  The left hand side of the assignment determines context so the @l2r{...}
  part.
  
  That strikes me as odd...  When perl goes to populate @l2r{a,b}, it
  seems to me that it would go through this process:
  
  - I have a slice here, so I'll loop over the slice elements
  - The first is a, so I'll pull a scalar off the list and assign it to
  $l2r{a}
  - The second is b, so I'll pull another scalar off the list and assign 
  it
  to $l2r{b}
  - Remaining scalars in the list are discarded
  
  Correct, except for the loop part.
  
  Why would $l2r{a} here be considered list context?
  
  It isn't, unless it's written as ( $l2r{a} ), then it's a list with
  one element.
  
  So I still don't understand what about @l2r{a,b} makes it evaluate the
  first (FILE... in list context instead of scalar context.
  
  The '@' sigil at the front of the variable name says that it is either
  an array or a slice and so it forces list context on the right hand side
  of the assignment.
 
 I think it finally clicked!
 
 It makes more sense to me that (FILE,FILE) is kind of the same thing as
 saying (@a,@b).  In list context @a returns the array as a list, but in
 scalar context @a returns the number of elements.  Obviously (@a,@b) returns
 the union of the two lists, not two scalars.  FILE is treated the same
 way.

Almost. It still depends on the left hand side. Try this:

@a = (10,20,30);
@b = (40,50,60);

$s = (@a,@b);
print $s\n;
#versus
($s) = (@a,@b);
print $s\n;


In the first case the @a and @b are evaluated in scalar context. Even 
though they are enclosed in braces.

Jenda
= [EMAIL PROTECTED] === http://Jenda.Krynicky.cz =
When it comes to wine, women and song, wizards are allowed 
to get drunk and croon as much as they like.
-- Terry Pratchett in Sourcery


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: populating a hash slice from a filehandle

2008-06-20 Thread Bryan R Harris

 Bryan R Harris wrote:
 
 John W. Krahn wrote:
 
 Bryan R Harris wrote:
 
 Jenda Krynicky wrote:
 
 Context. The FILEHANDLE returns a single line in scalar context and
 a list of all lines in a list context. And there is no such thing as
 a two-item-list context.
 
 So in the first case the assignment to @l2r{a,b} provides a list
 context so the very first FILE reads all the lines left in FILE,
 the second and third return an empty list. The first two lists are
 concatenated together and the first two items of the resulting list
 are assigned to $l2r{a} and $l2r{b}. And the rest of the list is
 forgotten. You'd have to do something like
 
 @l2r{a,b} = (scalar(FILE), scalar(FILE));
 or
 @l2r{a,b} = (FILE.'', FILE.'');
 
 to ensure that the FILE is evaluated in scalar context.
 
 Which part is forcing the list context?  The fact that the FILE is inside
 parenthesis () or the @l2r{...} part?
 
 The left hand side of the assignment determines context so the @l2r{...}
 part.
 
 That strikes me as odd...  When perl goes to populate @l2r{a,b}, it
 seems to me that it would go through this process:
 
 - I have a slice here, so I'll loop over the slice elements
 - The first is a, so I'll pull a scalar off the list and assign it to
 $l2r{a}
 - The second is b, so I'll pull another scalar off the list and assign it
 to $l2r{b}
 - Remaining scalars in the list are discarded
 
 Correct, except for the loop part.

 Why would $l2r{a} here be considered list context?
 
 It isn't, unless it's written as ( $l2r{a} ), then it's a list with
 one element.

So I still don't understand what about @l2r{a,b} makes it evaluate the
first (FILE... in list context instead of scalar context.


 What am I missing?
 
 Hard to say?  :-)

Indeed.

Maybe this one's just too complex for my little brain.

- B



-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: populating a hash slice from a filehandle

2008-06-20 Thread John W. Krahn

Bryan R Harris wrote:


John W. Krahn wrote:


Bryan R Harris wrote:


John W. Krahn wrote:


The left hand side of the assignment determines context so the @l2r{...}
part.


That strikes me as odd...  When perl goes to populate @l2r{a,b}, it
seems to me that it would go through this process:

- I have a slice here, so I'll loop over the slice elements
- The first is a, so I'll pull a scalar off the list and assign it to
$l2r{a}
- The second is b, so I'll pull another scalar off the list and assign it
to $l2r{b}
- Remaining scalars in the list are discarded


Correct, except for the loop part.


Why would $l2r{a} here be considered list context?


It isn't, unless it's written as ( $l2r{a} ), then it's a list with
one element.


So I still don't understand what about @l2r{a,b} makes it evaluate the
first (FILE... in list context instead of scalar context.


The '@' sigil at the front of the variable name says that it is either 
an array or a slice and so it forces list context on the right hand side 
of the assignment.



John
--
Perl isn't a toolbox, but a small machine shop where you
can special-order certain sorts of tools at low cost and
in short order.-- Larry Wall

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: populating a hash slice from a filehandle

2008-06-20 Thread Bryan R Harris

 Bryan R Harris wrote:
 
 John W. Krahn wrote:
 
 Bryan R Harris wrote:
 
 John W. Krahn wrote:
 
 The left hand side of the assignment determines context so the @l2r{...}
 part.
 
 That strikes me as odd...  When perl goes to populate @l2r{a,b}, it
 seems to me that it would go through this process:
 
 - I have a slice here, so I'll loop over the slice elements
 - The first is a, so I'll pull a scalar off the list and assign it to
 $l2r{a}
 - The second is b, so I'll pull another scalar off the list and assign it
 to $l2r{b}
 - Remaining scalars in the list are discarded
 
 Correct, except for the loop part.
 
 Why would $l2r{a} here be considered list context?
 
 It isn't, unless it's written as ( $l2r{a} ), then it's a list with
 one element.
 
 So I still don't understand what about @l2r{a,b} makes it evaluate the
 first (FILE... in list context instead of scalar context.
 
 The '@' sigil at the front of the variable name says that it is either
 an array or a slice and so it forces list context on the right hand side
 of the assignment.

I think it finally clicked!

It makes more sense to me that (FILE,FILE) is kind of the same thing as
saying (@a,@b).  In list context @a returns the array as a list, but in
scalar context @a returns the number of elements.  Obviously (@a,@b) returns
the union of the two lists, not two scalars.  FILE is treated the same
way.

Thanks!

- Bryan



-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: populating a hash slice from a filehandle

2008-06-19 Thread Bryan R Harris

 From: Bryan R Harris [EMAIL PROTECTED]
 Given an open filehandle, why don't these two things do the same thing?
 
 **
 @l2r{a,b} = (FILE, FILE);
 $c = FILE;
 
 **
 $l2r{a} = FILE;
 $l2r{b} = FILE;
 $c = FILE;
 
 **
 
 The first seems to be slurping the whole file into $l2r{b} and leaving $c
 undefined...  The second does what I want.  Doesn't seem to make sense.
 
 Context. The FILEHANDLE returns a single line in scalar context and
 a list of all lines in a list context. And there is no such thing as
 a two-item-list context.
 
 So in the first case the assignment to @l2r{a,b} provides a list
 context so the very first FILE reads all the lines left in FILE,
 the second and third return an empty list. The first two lists are
 concatenated together and the first two items of the resulting list
 are assigned to $l2r{a} and $l2r{b}. And the rest of the list is
 forgotten. You'd have to do something like
 
 @l2r{a,b} = (scalar(FILE), scalar(FILE));
 or
 @l2r{a,b} = (FILE.'', FILE.'');
 
 to ensure that the FILE is evaluated in scalar context.


Which part is forcing the list context?  The fact that the FILE is inside
parenthesis () or the @l2r{...} part?

Is every element of a list () contextualized as a list itself?

Thanks for the responses, Jeff and Jenda!

- Bryan




-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: populating a hash slice from a filehandle

2008-06-19 Thread John W. Krahn

Bryan R Harris wrote:

From: Bryan R Harris [EMAIL PROTECTED]

Given an open filehandle, why don't these two things do the same thing?

**
@l2r{a,b} = (FILE, FILE);
$c = FILE;

**
$l2r{a} = FILE;
$l2r{b} = FILE;
$c = FILE;

**

The first seems to be slurping the whole file into $l2r{b} and leaving $c
undefined...  The second does what I want.  Doesn't seem to make sense.

Context. The FILEHANDLE returns a single line in scalar context and
a list of all lines in a list context. And there is no such thing as
a two-item-list context.

So in the first case the assignment to @l2r{a,b} provides a list
context so the very first FILE reads all the lines left in FILE,
the second and third return an empty list. The first two lists are
concatenated together and the first two items of the resulting list
are assigned to $l2r{a} and $l2r{b}. And the rest of the list is
forgotten. You'd have to do something like

@l2r{a,b} = (scalar(FILE), scalar(FILE));
or
@l2r{a,b} = (FILE.'', FILE.'');

to ensure that the FILE is evaluated in scalar context.



Which part is forcing the list context?  The fact that the FILE is inside
parenthesis () or the @l2r{...} part?


The left hand side of the assignment determines context so the @l2r{...} 
part.




Is every element of a list () contextualized as a list itself?


A list is composed of zero or more scalars, if that's what you mean?



John
--
Perl isn't a toolbox, but a small machine shop where you
can special-order certain sorts of tools at low cost and
in short order.-- Larry Wall

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: populating a hash slice from a filehandle

2008-06-19 Thread Bryan R Harris

 Bryan R Harris wrote:
 From: Bryan R Harris [EMAIL PROTECTED]
 Given an open filehandle, why don't these two things do the same thing?
 
 **
 @l2r{a,b} = (FILE, FILE);
 $c = FILE;
 
 **
 $l2r{a} = FILE;
 $l2r{b} = FILE;
 $c = FILE;
 
 **
 
 The first seems to be slurping the whole file into $l2r{b} and leaving $c
 undefined...  The second does what I want.  Doesn't seem to make sense.
 Context. The FILEHANDLE returns a single line in scalar context and
 a list of all lines in a list context. And there is no such thing as
 a two-item-list context.
 
 So in the first case the assignment to @l2r{a,b} provides a list
 context so the very first FILE reads all the lines left in FILE,
 the second and third return an empty list. The first two lists are
 concatenated together and the first two items of the resulting list
 are assigned to $l2r{a} and $l2r{b}. And the rest of the list is
 forgotten. You'd have to do something like
 
 @l2r{a,b} = (scalar(FILE), scalar(FILE));
 or
 @l2r{a,b} = (FILE.'', FILE.'');
 
 to ensure that the FILE is evaluated in scalar context.
 
 
 Which part is forcing the list context?  The fact that the FILE is inside
 parenthesis () or the @l2r{...} part?
 
 The left hand side of the assignment determines context so the @l2r{...}
 part.

That strikes me as odd...  When perl goes to populate @l2r{a,b}, it
seems to me that it would go through this process:

- I have a slice here, so I'll loop over the slice elements
- The first is a, so I'll pull a scalar off the list and assign it to
$l2r{a}
- The second is b, so I'll pull another scalar off the list and assign it
to $l2r{b}
- Remaining scalars in the list are discarded

Why would $l2r{a} here be considered list context?

What am I missing?

- B

ps.  I'm often surprised at how little I seem to know even after 8 years of
perl scripting and monitoring this list...



-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: populating a hash slice from a filehandle

2008-06-19 Thread John W. Krahn

Bryan R Harris wrote:


John W. Krahn wrote:


Bryan R Harris wrote:



Jenda Krynicky wrote:

Context. The FILEHANDLE returns a single line in scalar context and
a list of all lines in a list context. And there is no such thing as
a two-item-list context.

So in the first case the assignment to @l2r{a,b} provides a list
context so the very first FILE reads all the lines left in FILE,
the second and third return an empty list. The first two lists are
concatenated together and the first two items of the resulting list
are assigned to $l2r{a} and $l2r{b}. And the rest of the list is
forgotten. You'd have to do something like

@l2r{a,b} = (scalar(FILE), scalar(FILE));
or
@l2r{a,b} = (FILE.'', FILE.'');

to ensure that the FILE is evaluated in scalar context.


Which part is forcing the list context?  The fact that the FILE is inside
parenthesis () or the @l2r{...} part?


The left hand side of the assignment determines context so the @l2r{...}
part.


That strikes me as odd...  When perl goes to populate @l2r{a,b}, it
seems to me that it would go through this process:

- I have a slice here, so I'll loop over the slice elements
- The first is a, so I'll pull a scalar off the list and assign it to
$l2r{a}
- The second is b, so I'll pull another scalar off the list and assign it
to $l2r{b}
- Remaining scalars in the list are discarded


Correct, except for the loop part.



Why would $l2r{a} here be considered list context?


It isn't, unless it's written as ( $l2r{a} ), then it's a list with 
one element.




What am I missing?


Hard to say?  :-)



John
--
Perl isn't a toolbox, but a small machine shop where you
can special-order certain sorts of tools at low cost and
in short order.-- Larry Wall

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




populating a hash slice from a filehandle

2008-06-18 Thread Bryan R Harris


Given an open filehandle, why don't these two things do the same thing?

**
@l2r{a,b} = (FILE, FILE);
$c = FILE;

**
$l2r{a} = FILE;
$l2r{b} = FILE;
$c = FILE;

**

The first seems to be slurping the whole file into $l2r{b} and leaving $c
undefined...  The second does what I want.  Doesn't seem to make sense.

TIA.

- Bryan




-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: populating a hash slice from a filehandle

2008-06-18 Thread Jeff Peng
On Thu, Jun 19, 2008 at 5:50 AM, Bryan R Harris
[EMAIL PROTECTED] wrote:


 Given an open filehandle, why don't these two things do the same thing?

 **
 @l2r{a,b} = (FILE, FILE);
 $c = FILE;


because @l2r{...} is a list, right?
so the statement above is in a list context.
so the second FILE will slurp all file content.

-- 
Jeff Peng - [EMAIL PROTECTED]
Professional Squid supports in China
http://www.ChinaSquid.com/

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: populating a hash slice from a filehandle

2008-06-18 Thread Jenda Krynicky
From: Bryan R Harris [EMAIL PROTECTED]
 Given an open filehandle, why don't these two things do the same thing?
 
 **
 @l2r{a,b} = (FILE, FILE);
 $c = FILE;
 
 **
 $l2r{a} = FILE;
 $l2r{b} = FILE;
 $c = FILE;
 
 **
 
 The first seems to be slurping the whole file into $l2r{b} and leaving $c
 undefined...  The second does what I want.  Doesn't seem to make sense.

Context. The FILEHANDLE returns a single line in scalar context and 
a list of all lines in a list context. And there is no such thing as 
a two-item-list context.

So in the first case the assignment to @l2r{a,b} provides a list 
context so the very first FILE reads all the lines left in FILE, 
the second and third return an empty list. The first two lists are 
concatenated together and the first two items of the resulting list 
are assigned to $l2r{a} and $l2r{b}. And the rest of the list is 
forgotten. You'd have to do something like

@l2r{a,b} = (scalar(FILE), scalar(FILE));
or
@l2r{a,b} = (FILE.'', FILE.'');

to ensure that the FILE is evaluated in scalar context.

HTH, Jenda
= [EMAIL PROTECTED] === http://Jenda.Krynicky.cz =
When it comes to wine, women and song, wizards are allowed 
to get drunk and croon as much as they like.
-- Terry Pratchett in Sourcery


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: split slice question

2008-05-11 Thread Dr.Ruud
Richard Lee schreef:

 I use this before (split slice ) but it's working bit funny now..
 it looks like it's splitting on '' instead of /|/ as I have specified
 below... ??

Look for quotemeta in perlre. 

-- 
Affijn, Ruud

Gewoon is een tijger.

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




split slice question

2008-05-10 Thread Richard Lee

I use this before (split slice ) but it's working bit funny now..

can someone tell me why??

it looks like it's splitting on '' instead of /|/ as I have specified 
below... ??


use strict;
use warnings;


my $array = q/hi|how|are|you|fine/;

my ($moe,$hae,$now) = (split(/|/,$array))[0,1,2];
print $moe $hae $now\n;

[EMAIL PROTECTED] ~]# ./!$
././split_practice.pl
h i |


--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: split slice question

2008-05-10 Thread Gunnar Hjalmarsson

Richard Lee wrote:


my ($moe,$hae,$now) = (split(/|/,$array))[0,1,2];


'|' is special in a regular expression and needs to be escaped.

--
Gunnar Hjalmarsson
Email: http://www.gunnar.cc/cgi-bin/contact.pl

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: Hash slice

2007-11-12 Thread Beginner
On 9 Nov 2007 at 20:04, Jenda Krynicky wrote:

 From: Beginner [EMAIL PROTECTED]
  On 9 Nov 2007 at 16:35, Jenda Krynicky wrote:
  
   From: Beginner [EMAIL PROTECTED]
#!/bin/perl

use strict;
use warnings;
use Data::Dumper;

my @keys = qw(fe fi fo thumb);
my @valone = 1..4;
my @valtwo = 10..14;
my %hash;
@[EMAIL PROTECTED] = [EMAIL PROTECTED],@valtwo];
   
   [...] creates an array reference. You want 
   
 @[EMAIL PROTECTED] = ( [EMAIL PROTECTED],[EMAIL PROTECTED]);
   
   Probably. Though it will only set the values for 'fe' and 'fi',
   because I only specify two values.

  
  What I was attempting was to have each key to be assigned the 
  coresponding items from the array. So it might look like something
  like:
  
  $VAR1 = {
  'fe' = [
  1,
  10
 ],
  'fi' = [
  2,
  11,
 ],
  'fo' = [
  3,
  13,
 ],
  'thumb' = [
  4,
  14,
  ]
  };
 
 @[EMAIL PROTECTED] = map [$valone[$_], $valtwo[$_]] (0..$#valone);
 
 
 The map produces a list of arrayrefs, each referenced array contains
 one item from @valone and one from @valtwo. The 0th element of the
 result, the 0th elements of @valone and @valtwo, etc.

Now there you go again with a beautifully simple use of map that does 
exactly what I want (do you need a comma before (0..$#valone)?).

I notice now that I wrote my example wrong. Each array was meant to 
have 4 items in (sorry Rob). So it should have been

my @valone = 1..4;
my @valtwo = 11..14;

There seems to be a bit of confusion over what I was trying to 
achieve. I typed out the output from Dumper I was expecting because I 
was/am not entirely sure what terms to use. The above operation looks 
like a hash slice to me albeit with another operator (map) involved.

Thanx for the help.
Dp.








-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: Hash slice

2007-11-12 Thread Jenda Krynicky
From:   Beginner [EMAIL PROTECTED]
 On 9 Nov 2007 at 20:04, Jenda Krynicky wrote:
  @[EMAIL PROTECTED] = map [$valone[$_], $valtwo[$_]] (0..$#valone);
  
  
  The map produces a list of arrayrefs, each referenced array contains
  one item from @valone and one from @valtwo. The 0th element of the
  result, the 0th elements of @valone and @valtwo, etc.
 
 Now there you go again with a beautifully simple use of map that does 
 exactly what I want (do you need a comma before (0..$#valone)?).

Yes, I was missing a comma. I usually use the 
map {} (list)
format that doesn't require the comma ... this is what happens if I 
change the habbits and don't test my code :-)
 
 I notice now that I wrote my example wrong. Each array was meant to 
 have 4 items in (sorry Rob). So it should have been
 
 my @valone = 1..4;
 my @valtwo = 11..14;
 
 There seems to be a bit of confusion over what I was trying to 
 achieve. I typed out the output from Dumper I was expecting because I 
 was/am not entirely sure what terms to use. The above operation looks 
 like a hash slice to me albeit with another operator (map) involved.

Yep, the Dumper output was exactly the right thing to use :-)

Jenda
= [EMAIL PROTECTED] === http://Jenda.Krynicky.cz =
When it comes to wine, women and song, wizards are allowed 
to get drunk and croon as much as they like.
-- Terry Pratchett in Sourcery


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Hash slice

2007-11-09 Thread Beginner
Hi all,

Is it possible to make a hash slice like so

my %hash;
@[EMAIL PROTECTED] = [EMAIL PROTECTED];

My efforts suggest not:

#!/bin/perl

use strict;
use warnings;
use Data::Dumper;

my @keys = qw(fe fi fo thumb);
my @vals = 1..4;
my %hash;
@[EMAIL PROTECTED] = [EMAIL PROTECTED];

print Dumper(\%hash);

$VAR1 = {
  'ARRAY(0x226d54)' = [
 1,
 2,
 3,
 4
   ]
};

Am I missing something or isn't this possible?
TIA.
Dp.


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: Hash slice

2007-11-09 Thread Rob Dixon

Beginner wrote:

Hi all,

Is it possible to make a hash slice like so

my %hash;
@[EMAIL PROTECTED] = [EMAIL PROTECTED];

My efforts suggest not:

#!/bin/perl

use strict;
use warnings;
use Data::Dumper;

my @keys = qw(fe fi fo thumb);
my @vals = 1..4;
my %hash;
@[EMAIL PROTECTED] = [EMAIL PROTECTED];

print Dumper(\%hash);

$VAR1 = {
  'ARRAY(0x226d54)' = [
 1,
 2,
 3,
 4
   ]
};

Am I missing something or isn't this possible?


Hey Dermot

It's certainly possible, but I'm not sure why you've taken a reference
to your key and value arrays. [EMAIL PROTECTED] is a single scalar value, as is
[EMAIL PROTECTED], so you're creating a single hash element. Perl has had to
stringify the reference to @keys as Perl hash keys must be strings.
The hash value is a reference you your @vals array which contains the
values 1 through 4 as Dumper shows.


That you need is simply

 @[EMAIL PROTECTED] = @vals;

which you will find has the effect you expect.

HTH,

Rob

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: Hash slice

2007-11-09 Thread Jenda Krynicky
From: Beginner [EMAIL PROTECTED]
 #!/bin/perl
 
 use strict;
 use warnings;
 use Data::Dumper;
 
 my @keys = qw(fe fi fo thumb);
 my @valone = 1..4;
 my @valtwo = 10..14;
 my %hash;
 @[EMAIL PROTECTED] = [EMAIL PROTECTED],@valtwo];

[...] creates an array reference. You want 

  @[EMAIL PROTECTED] = ( [EMAIL PROTECTED],[EMAIL PROTECTED]);

Probably. Though it will only set the values for 'fe' and 'fi', 
because I only specify two values.
 
Jenda
= [EMAIL PROTECTED] === http://Jenda.Krynicky.cz =
When it comes to wine, women and song, wizards are allowed 
to get drunk and croon as much as they like.
-- Terry Pratchett in Sourcery


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: Hash slice

2007-11-09 Thread Beginner
On 9 Nov 2007 at 14:59, Rob Dixon wrote:

 Beginner wrote:
  Hi all,
  
  Is it possible to make a hash slice like so

 Hey Dermot

Hi Rob,
 
 It's certainly possible, but I'm not sure why you've taken a reference
 to your key and value arrays. [EMAIL PROTECTED] is a single scalar value, as 
 is
 [EMAIL PROTECTED], so you're creating a single hash element. Perl has had to
 stringify the reference to @keys as Perl hash keys must be strings.
 The hash value is a reference you your @vals array which contains the
 values 1 through 4 as Dumper shows.

I see, scalar used where list expected.

How about this:

#!/bin/perl

use strict;
use warnings;
use Data::Dumper;

my @keys = qw(fe fi fo thumb);
my @valone = 1..4;
my @valtwo = 10..14;
my %hash;
@[EMAIL PROTECTED] = [EMAIL PROTECTED],@valtwo];

print Dumper(\%hash);
$VAR1 = {
  'fo' = undef,
  'fi' = undef,
  'fe' = [
1,
2,
3,
4,
10,
11,
12,
13,
14
  ],
  'thumb' = undef
};

I can't see why you can't create a slice hows values are arrays or 
why all the values are assigned to the first key.

Not a biggy. I can work around it but I'm interested to know.
Thanx,
Dp.




-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: Hash slice

2007-11-09 Thread Beginner
On 9 Nov 2007 at 16:35, Jenda Krynicky wrote:

 From: Beginner [EMAIL PROTECTED]
  #!/bin/perl
  
  use strict;
  use warnings;
  use Data::Dumper;
  
  my @keys = qw(fe fi fo thumb);
  my @valone = 1..4;
  my @valtwo = 10..14;
  my %hash;
  @[EMAIL PROTECTED] = [EMAIL PROTECTED],@valtwo];
 
 [...] creates an array reference. You want 
 
   @[EMAIL PROTECTED] = ( [EMAIL PROTECTED],[EMAIL PROTECTED]);
 
 Probably. Though it will only set the values for 'fe' and 'fi', 
 because I only specify two values.
  

What I was attempting was to have each key to be assigned the 
coresponding items from the array. So it might look like something 
like:

$VAR1 = {
'fe' = [
1,
10
   ],
'fi' = [
2,
11,
   ],
'fo' = [
3,
13,
   ],
'thumb' = [
4,
14,
]
};

(yes I typed that by hand) and not 

$VAR1 = {
  'fo' = undef,
  'fi' = [
10,
11,
12,
13,
14
  ],
  'fe' = [
1,
2,
3,
4
  ],
  'thumb' = undef
};


But I see why it's hasn't worked.
Dp,


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: Hash slice

2007-11-09 Thread [EMAIL PROTECTED]
On Nov 9, 4:09 pm, [EMAIL PROTECTED] (Beginner) wrote:
 On 9 Nov 2007 at 16:35, Jenda Krynicky wrote:

 What I was attempting was to have each key to be assigned the
 coresponding items from the array. So it might look like something
 like:

Right, so your question has nothing to do with hash slices.

Learning to break down your problem is and important skill in
programming.

What you seek is a way  swap (transpose) the axes of a list of array
references.

ie. you want the list ([1,2],[3,4],[5,6]) to become ([1,3,5],[2,4,6])

There's no built-in way to do that but I'm prepared to bet there are
several modules on CPAN that provide this (I just don't seem to be
able to find them right now).

I have a strange feeling there is a way to do this in Perl6.


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: Hash slice

2007-11-09 Thread [EMAIL PROTECTED]
On Nov 9, 3:35 pm, [EMAIL PROTECTED] (Jenda Krynicky) wrote:

   @[EMAIL PROTECTED] = ( [EMAIL PROTECTED],[EMAIL PROTECTED]);

Note that _can_ also be written

 @[EMAIL PROTECTED] = \( @valone, @valtwo);

But IMNSHO it this syntax should _only_ be used in code that is
intended as part of a response to the question what's the most
confusing feature of Perl5 syntax?



-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: Hash slice

2007-11-09 Thread Rob Dixon

Beginner wrote:


On 9 Nov 2007 at 14:59, Rob Dixon wrote:


Beginner wrote:


Is it possible to make a hash slice like so
 

It's certainly possible, but I'm not sure why you've taken a reference
to your key and value arrays. [EMAIL PROTECTED] is a single scalar value, as is
[EMAIL PROTECTED], so you're creating a single hash element. Perl has had to
stringify the reference to @keys as Perl hash keys must be strings.
The hash value is a reference you your @vals array which contains the
values 1 through 4 as Dumper shows.


I see, scalar used where list expected.


Nope, not this time! But you used a hash slice of one element:

 @[EMAIL PROTECTED] = [EMAIL PROTECTED];

is the same as

 my ($k, $v) = ([EMAIL PROTECTED], [EMAIL PROTECTED]);
 @hash{$k} = $v;

which is ok, but does the same thing as

 $hash{$k} = $v;


How about this:

#!/bin/perl

use strict;
use warnings;
use Data::Dumper;

my @keys = qw(fe fi fo thumb);
my @valone = 1..4;
my @valtwo = 10..14;
my %hash;
@[EMAIL PROTECTED] = [EMAIL PROTECTED],@valtwo];

print Dumper(\%hash);
$VAR1 = {
  'fo' = undef,
  'fi' = undef,
  'fe' = [
1,
2,
3,
4,
10,
11,
12,
13,
14
  ],
  'thumb' = undef
};


Alright, that's equivalent to

my @vals = (@valone, @valtwo);
my $v = [EMAIL PROTECTED];

@[EMAIL PROTECTED] = $v;

and because there are four keys in the slice and only one value, the
trailing three get set to undef.

I can't see why you can't create a slice hows values are arrays or 
why all the values are assigned to the first key.


Not a biggy. I can work around it but I'm interested to know.


Each hash element must have exactly one key and one value, but you've
got an array of four keys and a list of nine values (1, 2, 3, 4, 10,
11, 12, 13, 14). Four keys can't be paired with nine values! What do
you actually want here?

@[EMAIL PROTECTED] = (@valone, @valtwo);

pairs the first four values to the keys in the array and throws away
the remaining five.

Don't forget that a reference is a single scalar value, so both

 [EMAIL PROTECTED]

and

 [EMAIL PROTECTED], @valtwo]

are one scalar.

HTH,

Rob

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: Hash slice

2007-11-09 Thread Paul Lalli
On Nov 9, 11:09 am, [EMAIL PROTECTED] (Beginner) wrote:
 What I was attempting was to have each key to be assigned the
 coresponding items from the array.

Why didn't you just say that in the first place, rather than letting
everyone guess as to what you wanted?

 So it might look like something
 like:

 $VAR1 = {
 'fe' = [
 1,
 10
],
 'fi' = [
 2,
 11,
],
 'fo' = [
 3,
 13,
],
 'thumb' = [
 4,
 14,
 ]

 };


#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
use List::MoreUtils 'each_array';
my @keys = qw/fe fi fo fum/;
my @one = (1..4);
my @two = (11..14);
my $it = each_array @one, @two;
my %h;
@[EMAIL PROTECTED] = map { [ $it-() ] } [EMAIL PROTECTED];
print Dumper(\%h);
__END__

Paul Lalli


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: Hash slice

2007-11-09 Thread Jenda Krynicky
From: Beginner [EMAIL PROTECTED]
 On 9 Nov 2007 at 16:35, Jenda Krynicky wrote:
 
  From: Beginner [EMAIL PROTECTED]
   #!/bin/perl
   
   use strict;
   use warnings;
   use Data::Dumper;
   
   my @keys = qw(fe fi fo thumb);
   my @valone = 1..4;
   my @valtwo = 10..14;
   my %hash;
   @[EMAIL PROTECTED] = [EMAIL PROTECTED],@valtwo];
  
  [...] creates an array reference. You want 
  
@[EMAIL PROTECTED] = ( [EMAIL PROTECTED],[EMAIL PROTECTED]);
  
  Probably. Though it will only set the values for 'fe' and 'fi', 
  because I only specify two values.
   
 
 What I was attempting was to have each key to be assigned the 
 coresponding items from the array. So it might look like something 
 like:
 
 $VAR1 = {
   'fe' = [
   1,
   10
  ],
   'fi' = [
   2,
   11,
  ],
   'fo' = [
   3,
   13,
  ],
   'thumb' = [
   4,
   14,
   ]
 };

@[EMAIL PROTECTED] = map [$valone[$_], $valtwo[$_]] (0..$#valone);


The map produces a list of arrayrefs, each referenced array contains 
one item from @valone and one from @valtwo. The 0th element of the 
result, the 0th elements of @valone and @valtwo, etc.

Jenda
= [EMAIL PROTECTED] === http://Jenda.Krynicky.cz =
When it comes to wine, women and song, wizards are allowed 
to get drunk and croon as much as they like.
-- Terry Pratchett in Sourcery


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/




Re: hashref ref ref slice

2006-05-03 Thread Karjala

Try this:
map {$_-{text}} @[EMAIL PROTECTED]

Ryan Perry wrote:

@[EMAIL PROTECTED]{text}

I want to get all the text values for a set of keys in a hashref, 
but the above code always gives me only the first in @sortedkeys.


Thanks for any assistance!

Ryan

--To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response








--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: hashref ref ref slice

2006-05-03 Thread Karjala

And this will work also:

map {$tmp-{$_}-{text}} @sortedkeys


Karjala wrote:

Try this:
map {$_-{text}} @[EMAIL PROTECTED]

Ryan Perry wrote:

@[EMAIL PROTECTED]{text}

I want to get all the text values for a set of keys in a hashref, 
but the above code always gives me only the first in @sortedkeys.


Thanks for any assistance!

Ryan

--To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response












--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




hashref ref ref slice

2006-05-02 Thread Ryan Perry

@[EMAIL PROTECTED]{text}

I want to get all the text values for a set of keys in a hashref,  
but the above code always gives me only the first in @sortedkeys.


Thanks for any assistance!

Ryan

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: hash slice/exists vs. grep benchmark weirdness...

2005-01-26 Thread Marcello
JupiterHost.Net ha scritto:
In benchmarking some code I've come across something I did not expect:
slice:
use strict;
use warnings;
my @k=qw(1 2 3 4 5 6);
my %n;@[EMAIL PROTECTED] = @k;
print hi if exists $n{1};
print hi if exists $n{3};
print hi if exists $n{5};
print hi if exists $n{7};
print hi if exists $n{9};
print hi if exists $n{11};
grep:
use strict;
use warnings;
my @k=qw(1 2 3 4 5 6);
print hi if grep /^1$/, @k;
print hi if grep /^3$/, @k;
print hi if grep /^5$/, @k;
print hi if grep /^7$/, @k;
print hi if grep /^9$/, @k;
print hi if grep /^11$/, @k;

Benchmark: timing 500 iterations of grep, slice...
  grep: 3.65945 wallclock secs ( 2.33 usr +  0.04 sys =  2.37 CPU) @ 
2109704.64/s (n=500)
 slice: 2.37966 wallclock secs ( 2.52 usr + -0.01 sys =  2.51 CPU) @ 
1992031.87/s (n=500)
   Rate slice  grep
slice 1992032/s--   -6%
grep  2109705/s6%--

I would've thought the slice and then use exists would have been 
faster then greping the entire array each time and using regexes when 
you check it. but its consistently faster by an average 6-10%

Any ideas why that might be?
Just for curiosity, I ran a slightly different version of your benchmarks:
code source=slice-bench.pl
use strict;
use warnings;
use diagnostics;
my @k=qw(1 2 3 4 5 6);
my %n;
@[EMAIL PROTECTED] = @k;
my $times = 500;
my $dummy;
while($times--) {
$dummy=1 if exists $n{1};
$dummy=1 if exists $n{3};
$dummy=1 if exists $n{5};
$dummy=1 if exists $n{7};
$dummy=1 if exists $n{9};
$dummy=1 if exists $n{11};
}
/code
code source=grep-bench.pl
use strict;
use warnings;
use diagnostics;
my @k=qw(1 2 3 4 5 6);
my $times = 500;
my $dummy;
while($times--) {
$dummy=1 if grep /^1$/, @k;
$dummy=1 if grep /^3$/, @k;
$dummy=1 if grep /^5$/, @k;
$dummy=1 if grep /^7$/, @k;
$dummy=1 if grep /^9$/, @k;
$dummy=1 if grep /^11$/, @k;
}
/code
The results were:
log shelltype=bash
[EMAIL PROTECTED] time perl slice-bench.pl
9.15user 0.01system 0:09.89elapsed 92%CPU (0avgtext+0avgdata 0maxresident)k
0inputs+0outputs (0major+1015minor)pagefaults 0swaps
[EMAIL PROTECTED] time perl grep-bench.pl
67.52user 0.01system 1:12.97elapsed 92%CPU (0avgtext+0avgdata 0maxresident)k
0inputs+0outputs (0major+1015minor)pagefaults 0swaps
/log
The slice version took about 10 seconds, the grep one took more than 1 
minute.

Marcello
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response



Re: hash slice/exists vs. grep benchmark weirdness...

2005-01-26 Thread JupiterHost.Net

The slice version took about 10 seconds, the grep one took more than 1 
minute.

Marcello
Thanks Marcello!
Your example, John's. and renards have been very helpful to help see the 
point someone else was trying to make about watching what you include in 
your benchmark.

I appreciate your time :)
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response



Re: hash slice/exists vs. grep benchmark weirdness...

2005-01-26 Thread JupiterHost.Net

renard wrote:
BE AWARE THAT THE BENCHMARK PROVIDES INCORRECT RESULTS.
Thnaks, I was aware of that, but still wanted a general idea :)
The tested code is within an anonymous subroutine while this does 
executes, the results differ dramitcally from the results when the 
tested code is enclosed within single quotation marks.!!!

I do not know why the great difference ... perhaps the experts might be 
able to explain the difference. This is not the first time that I 
observe this divergence.

The test results below show when the tested code is enclosed within 
single quotation marks, the 'exists' code has a 40% advantage.
over the 'grep_e' code but has a 1100% advantage over the grep_e code 
when enclosed within an anonymous subroutine. The code enclosed inside 
the anonympous subroutine takes substantially longer to execute.

I tend to believe that the results for the single quotation mark is more 
accurate.
I'll use that info in the future, thanks!
So buyer beware ...
[snip]
Benchmark: timing 100 iterations of exists, grep_e, grep_r, hash...
   exists: 2.99903 wallclock secs ( 2.97 usr +  0.01 sys =  2.98 CPU) @ 
335232.99/s (n=100)
   grep_e: 4.14286 wallclock secs ( 4.16 usr +  0.00 sys =  4.16 CPU) @ 
240615.98/s (n=100)
   grep_r: 3.93865 wallclock secs ( 3.92 usr +  0.00 sys =  3.92 CPU) @ 
254971.95/s (n=100)
 hash: 3.01261 wallclock secs ( 3.00 usr +  0.00 sys =  3.00 CPU) @ 
33.33/s (n=100)

  Rate grep_e grep_r   hash exists
grep_e 240616/s ---6%   -28%   -28%
grep_r 254972/s 6% --   -24%   -24%
hash   33/s39%31% ---1%
exists 335233/s39%31% 1% --
Benchmark: timing 100 iterations of exists, grep_e, grep_r, hash...
   exists: 7.63617 wallclock secs ( 7.56 usr +  0.00 sys =  7.56 CPU) @ 
13.66/s (n=100)
   grep_e: 14.9662 wallclock secs (14.72 usr +  0.00 sys = 14.72 CPU) @ 
67939.40/s (n=100)
   grep_r: 95.0288 wallclock secs (93.33 usr +  0.03 sys = 93.36 CPU) @ 
10711.34/s (n=100)
 hash: 15.6237 wallclock secs (15.50 usr +  0.02 sys = 15.52 CPU) @ 
64449.60/s (n=100)

  Rate grep_r   hash grep_e exists
grep_r  10711/s --   -83%   -84%   -92%
hash64450/s   502% ---5%   -51%
grep_e  67939/s   534% 5% --   -49%
exists 132223/s  1134%   105%95% --
Excellent! I beleive from all the different tests I will be going with 
exists *and* more craefull how/what I benchmark :)

Thanks for your time!
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response



Re: hash slice/exists vs. grep benchmark weirdness...

2005-01-25 Thread JupiterHost.Net
You have to stop spending so much time playing with all this bogus
benchmarking :)
It not bogus :) Its an example to find the best method for a project.
If you prefer I'll ask the question I was trying to answer with the 
benchmark:

Assuming you have an array of 0-15 elements is it quicker/more efficient to:
 1) create a hash slice and use exists when checking for specific ones
or
 2) grep a regex out of the array when checking for specific ones
slice:
use strict;
use warnings;
my @k=qw(1 2 3 4 5 6);
my %n;@[EMAIL PROTECTED] = @k;
print hi if exists $n{1};
print hi if exists $n{3};
print hi if exists $n{5};
print hi if exists $n{7};
print hi if exists $n{9};
print hi if exists $n{11};
grep:
use strict;
use warnings;
my @k=qw(1 2 3 4 5 6);
print hi if grep /^1$/, @k;
print hi if grep /^3$/, @k;
print hi if grep /^5$/, @k;
print hi if grep /^7$/, @k;
print hi if grep /^9$/, @k;
print hi if grep /^11$/, @k;
Benchmark: timing 500 iterations of grep, slice...
  grep: 3.65945 wallclock secs ( 2.33 usr +  0.04 sys =  2.37 CPU) 
@ 2109704.64/s (n=500)
 slice: 2.37966 wallclock secs ( 2.52 usr + -0.01 sys =  2.51 CPU) 
@ 1992031.87/s (n=500)
   Rate slice  grep
slice 1992032/s--   -6%
grep  2109705/s6%--

I would've thought the slice and then use exists would have been 
faster then greping the entire array each time and using regexes when 
you check it. but its consistently faster by an average 6-10%

Any ideas why that might be?
Well, first -- you're creating the hash inside the benchmark loop,
which is not particularly light-weight.
Good point,
although in the real world app I'll have an array already so I want to 
see if its quicker to:
 - make the hash via a slice and use exists
or
 - just grep the whole array each time with a regex
If I use
 my %hash = qw(1..2);
and exists
vs.
 my @array = qw(1..1);
IE - no slice

then exists is a bit faster 2% or so, the problem is I start with an 
array I have no control over.

So, I'd have to do a slice to get the hash (or loop through it or 
otherwise do something to get the hash)

Second:  You're using pathologically small lists.  Try running it with
10,000 elements instead of ten.
that makes them about even, with slice being 1% faster at times, however 
the size of the array in the real world app are similar to the original 
benchmark

Third:  Premature optimization is a terrible thing.
Premature? Could you elaborate?
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response



Re: hash slice/exists vs. grep benchmark weirdness...

2005-01-25 Thread mgoland


- Original Message -
From: JupiterHost.Net [EMAIL PROTECTED]
Date: Tuesday, January 25, 2005 11:01 am
Subject: Re: hash slice/exists vs. grep benchmark weirdness...

  You have to stop spending so much time playing with all this bogus
  benchmarking :)
 
 It not bogus :) Its an example to find the best method for a project.
 
 If you prefer I'll ask the question I was trying to answer with 
 the 
 benchmark:
 
 Assuming you have an array of 0-15 elements is it quicker/more 
 efficient to:
 
  1) create a hash slice and use exists when checking for specific 
 onesor
  2) grep a regex out of the array when checking for specific ones
 
 slice:
 use strict;
 use warnings;
 my @k=qw(1 2 3 4 5 6);
 my %n;@[EMAIL PROTECTED] = @k;
 print hi if exists $n{1};
 print hi if exists $n{3};
 print hi if exists $n{5};
 print hi if exists $n{7};
 print hi if exists $n{9};
 print hi if exists $n{11};
 
 grep:
 use strict;
 use warnings;
 my @k=qw(1 2 3 4 5 6);
 print hi if grep /^1$/, @k;
 print hi if grep /^3$/, @k;
 print hi if grep /^5$/, @k;
 print hi if grep /^7$/, @k;
 print hi if grep /^9$/, @k;
 print hi if grep /^11$/, @k;
 
 Benchmark: timing 500 iterations of grep, slice...
grep: 3.65945 wallclock secs ( 2.33 usr +  0.04 sys =  
 2.37 CPU) 
 @ 2109704.64/s (n=500)
   slice: 2.37966 wallclock secs ( 2.52 usr + -0.01 sys =  
 2.51 CPU) 
 @ 1992031.87/s (n=500)
 Rate slice  grep
 slice 1992032/s--   -6%
 grep  2109705/s6%--
 
 I would've thought the slice and then use exists would have 
 been 
 faster then greping the entire array each time and using 
 regexes when 
 you check it. but its consistently faster by an average 6-10%
 
 Any ideas why that might be?
  
  Well, first -- you're creating the hash inside the benchmark loop,
  which is not particularly light-weight.
 
 Good point,
 although in the real world app I'll have an array already so I 
 want to 
 see if its quicker to:
  - make the hash via a slice and use exists
 or
  - just grep the whole array each time with a regex
 If I use
  my %hash = qw(1..2);
 and exists
 vs.
  my @array = qw(1..1);
 IE - no slice
 
 then exists is a bit faster 2% or so, the problem is I start with 
 an 
 array I have no control over.
 
 So, I'd have to do a slice to get the hash (or loop through it or 
 otherwise do something to get the hash)
 
  Second:  You're using pathologically small lists.  Try running 
 it with
  10,000 elements instead of ten.
 
 that makes them about even, with slice being 1% faster at times, 
 however 
 the size of the array in the real world app are similar to the 
 original 
 benchmark
 
  Third:  Premature optimization is a terrible thing.
 
 Premature? Could you elaborate?

Just as an FYI, you don't need exists in your code at all. It is just a waste 
of time in your example. Should be beter writen as:

print hi if $n{11};

 
 -- 
 To unsubscribe, e-mail: [EMAIL PROTECTED]
 For additional commands, e-mail: [EMAIL PROTECTED]
 http://learn.perl.org/ http://learn.perl.org/first-response
 
 
 


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: hash slice/exists vs. grep benchmark weirdness...

2005-01-25 Thread JupiterHost.Net

Just as an FYI, you don't need exists in your code at all. It is just a 
waste of time in your example. Should be beter writen as:
print hi if $n{11};
What if it's value is 0, '', or undef? It would exist but your test 
would miss it :)

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response



RE: hash slice/exists vs. grep benchmark weirdness...

2005-01-25 Thread Thomas Bätzler
 
[EMAIL PROTECTED] suggested:
 Just as an FYI, you don't need exists in your code at all. 
 It is just a waste of time in your example. Should be beter writen as:
 
 print hi if $n{11};

Bad idea, if you consider this:

$n{'oops'} = 0;
print hi if $n{'oops'};
print ho if exists $n{'oops'};

HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




RE: hash slice/exists vs. grep benchmark weirdness...

2005-01-25 Thread Bakken, Luke
  You have to stop spending so much time playing with all this bogus
  benchmarking :)
 
 It not bogus :) Its an example to find the best method for a project.
 
 If you prefer I'll ask the question I was trying to answer with the 
 benchmark:
 
 Assuming you have an array of 0-15 elements is it 
 quicker/more efficient to:
 
   1) create a hash slice and use exists when checking for 
 specific ones
 or
   2) grep a regex out of the array when checking for specific ones

If you're going to be looking for something in an array over and over
again, perhaps you shouldn't be using an array as your data structure.

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: hash slice/exists vs. grep benchmark weirdness...

2005-01-25 Thread mgoland


- Original Message -
From: JupiterHost.Net [EMAIL PROTECTED]
Date: Tuesday, January 25, 2005 11:37 am
Subject: Re: hash slice/exists vs. grep benchmark weirdness...

 
  
  Just as an FYI, you don't need exists in your code at all. It 
 is just a waste of time in your example. Should be beter writen as:
  
  print hi if $n{11};
 
 What if it's value is 0, '', or undef? It would exist but your 
 test 
 would miss it :)

In that case defined would be a beter function to use.


 
 -- 
 To unsubscribe, e-mail: [EMAIL PROTECTED]
 For additional commands, e-mail: [EMAIL PROTECTED]
 http://learn.perl.org/ http://learn.perl.org/first-response
 
 
 


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: hash slice/exists vs. grep benchmark weirdness...

2005-01-25 Thread Lawrence Statton
  You have to stop spending so much time playing with all this bogus
  benchmarking :)
 
 It not bogus :) Its an example to find the best method for a project.
 

And I'll reiterate more clearly.  Benchmarking is *not* the tool to find
the best method.

The BEST method for a project is that method which is self evident and
maintainable.  ONLY AFTER you determine that you have missed your
performance envelope, do you go back through your code using rakes and
shovels and implements of destruction to find the slow parts.  Early
Optimization Is The Root of All Evil.  

 If you prefer I'll ask the question I was trying to answer with the 
 benchmark:
 
 Assuming you have an array of 0-15 elements is it quicker/more efficient to:
 
   1) create a hash slice and use exists when checking for specific ones
 or
   2) grep a regex out of the array when checking for specific ones
 

Both.  Each one will 'win' in terms of total execution time for some
set of conditions, none of which have been expressed in the problem.
(For example, will the keys always be small integers?  How complex
will they be?  This will have a tremendous impact on the performance
of the match operator.)

And, in fact, you yourself may not know a priori what the conditions
will be - which is why I say (again because you really need to hear
this): Premature Optimization Is The Root of All Evil.

Write your code so you can maintain it.  The microseconds will take
care of themselves.  The programmers' time is orders of magnitude more
costly than the computers', and your value is (hopefully!) increasing,
while the cost of computational oomph is (thankfully) decreasing.

Now, as to this specific question -- use whichever idiom you are more
comfortable with.  Furthermore, that is a tiny implementation detail
-- in the Big Picture, it won't matter a gnats eyebrow.

Finally, there were serious errors in your methodology in your
original benchmark.  It turns out the printing dominated the total
execution time, such that the variance between the two different
selection methods were pushed down into the noise.  When I benchmarked
using lists of 10 elements searching for five random members in
the list, the exists-in-hash version was about 10 times faster
for *JUST THE SELECTION OPERATION* than the grep-the-list version. 

-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
Lawrence Statton - [EMAIL PROTECTED] s/aba/c/g
Computer  software  consists of  only  two  components: ones  and
zeros, in roughly equal proportions.   All that is required is to
sort them into the correct order.

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: hash slice/exists vs. grep benchmark weirdness...

2005-01-25 Thread JupiterHost.Net

print hi if $n{11};
What if it's value is 0, '', or undef? It would exist but your 
test 
would miss it :)

In that case defined would be a beter function to use.
ok, but I'm still not interested in the value of the key I;'m interested 
inthe key, so why not exists since its made for hashes :)

I simply asked what if to illustrate why if $n{11} is not better 
than exists $n{11} in this case.

So the original question remains:
Which is faster:
1) slice the array into a has and do exists $hsh{key}
or
2) just grep a regex on the array
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response



Re: hash slice/exists vs. grep benchmark weirdness...

2005-01-25 Thread JupiterHost.Net

Bakken, Luke wrote:
You have to stop spending so much time playing with all this bogus
benchmarking :)
It not bogus :) Its an example to find the best method for a project.
If you prefer I'll ask the question I was trying to answer with the 
benchmark:

Assuming you have an array of 0-15 elements is it 
quicker/more efficient to:

 1) create a hash slice and use exists when checking for 
specific ones
or
 2) grep a regex out of the array when checking for specific ones

If you're going to be looking for something in an array over and over
again, perhaps you shouldn't be using an array as your data structure.
Hence, my original question :)
I have an array not matter what.
So should I slice it into a hash and do exists or skip the slice and 
grep a regex on the array each time :)

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response



Re: hash slice/exists vs. grep benchmark weirdness...

2005-01-25 Thread JupiterHost.Net
Thanks for your input :)
Finally, there were serious errors in your methodology in your
Serious? I thought in the Big Picture, it won't matter a gnats eyebrow. :)
original benchmark.  It turns out the printing dominated the total
That is why I made both identical except for the difference I'm 
concerned with.

execution time, such that the variance between the two different
selection methods were pushed down into the noise.  When I benchmarked
using lists of 10 elements searching for five random members in
the list, the exists-in-hash version was about 10 times faster
for *JUST THE SELECTION OPERATION* than the grep-the-list version. 
Excellent, what code did you benchmark?
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response



Re: hash slice/exists vs. grep benchmark weirdness...

2005-01-25 Thread Lawrence Statton
 Thanks for your input :)

No problem -- I really do enjoy this.  However, I do have some actual
WORK that I need to do today :(  

  Finally, there were serious errors in your methodology in your
 
 Serious? I thought in the Big Picture, it won't matter a gnats eyebrow. :)

And I stand by that ... Such is the fallacy of the benchmark: hah!
Technique Foo was ten times faster than Technique Bar!  But, if one
takes 5 microseconds and the other takes 50, they're both going to be
blown out of the water by the first page-fault that crosses their
path, or waiting for an I/O operation to complete, or someone moving
the mouse causing the screen to refresh, or a million other things
that will make that 45 microsecond difference pale in comparison.

 
  original benchmark.  It turns out the printing dominated the total
 
 That is why I made both identical except for the difference I'm 
 concerned with.

Still poor methodology -- A thought-experiment.  I am testing two
different implementations -- now $DEITY knows that one of them will
take 10 milliseconds to execute, and the other an entire second.  (I,
however, not being omniscient don't know that -- hence my benchmarking
test).  

I put them into a test-crib with a second function that takes
precisely 24-hours to complete.  So, one of them takes 86400.01
seconds, and the other takes 86401.00 seconds.  Now, assume that the
24-hour extraneous function really might vary randomly plus or minus
five minutes.  Suddenly that variance in the spurious function will
totally swamp the variance I am trying to measure between the two
implementations.

In your benchmark, you did precisely that -- by putting a function
that takes a relatively very-very-long and randomly-variable amount of
time (printing) inside the function you are trying to test, you are
basically destroying the exact number you are trying to compute, and
have merely computed the deviation of the print operator.

-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
Lawrence Statton - [EMAIL PROTECTED] s/aba/c/g
Computer  software  consists of  only  two  components: ones  and
zeros, in roughly equal proportions.   All that is required is to
sort them into the correct order.




-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: hash slice/exists vs. grep benchmark weirdness...

2005-01-25 Thread John W. Krahn
JupiterHost.Net wrote:
In benchmarking some code I've come across something I did not expect:
slice:
use strict;
use warnings;
my @k=qw(1 2 3 4 5 6);
my %n;@[EMAIL PROTECTED] = @k;
print hi if exists $n{1};
print hi if exists $n{3};
print hi if exists $n{5};
print hi if exists $n{7};
print hi if exists $n{9};
print hi if exists $n{11};
grep:
use strict;
use warnings;
my @k=qw(1 2 3 4 5 6);
print hi if grep /^1$/, @k;
print hi if grep /^3$/, @k;
print hi if grep /^5$/, @k;
print hi if grep /^7$/, @k;
print hi if grep /^9$/, @k;
print hi if grep /^11$/, @k;

Benchmark: timing 500 iterations of grep, slice...
  grep: 3.65945 wallclock secs ( 2.33 usr +  0.04 sys =  2.37 CPU) @ 
2109704.64/s (n=500)
 slice: 2.37966 wallclock secs ( 2.52 usr + -0.01 sys =  2.51 CPU) @ 
1992031.87/s (n=500)
   Rate slice  grep
slice 1992032/s--   -6%
grep  2109705/s6%--

I would've thought the slice and then use exists would have been 
faster then greping the entire array each time and using regexes when 
you check it. but its consistently faster by an average 6-10%

Any ideas why that might be?
Well, let's see:
#!/usr/bin/perl
use warnings;
use strict;
use Benchmark 'cmpthese';
my @k = qw( 1 2 3 4 5 6 );
cmpthese( -10, {
exists  = sub {
my $count = 0;
my %hash;
@hash{ @k } = ();
for my $num ( 1, 3, 5, 7, 9, 11 ) {
$count++ if exists $hash{ $num };
}
return $count;
},
hash= sub {
my $count = 0;
my %hash = map { $_ = 1 } @k;
for my $num ( 1, 3, 5, 7, 9, 11 ) {
$count++ if $hash{ $num };
}
return $count;
},
grep_r  = sub {
my $count = 0;
my @array = @k;
for my $num ( 1, 3, 5, 7, 9, 11 ) {
$count++ if grep /^$num$/, @array;
}
return $count;
},
grep_e  = sub {
my $count = 0;
my @array = @k;
for my $num ( 1, 3, 5, 7, 9, 11 ) {
$count++ if grep $_ == $num, @array;
}
return $count;
},
} );
Produces the result (on my computer):
  Rate grep_r grep_e   hash exists
grep_r  4838/s --   -81%   -83%   -90%
grep_e 25923/s   436% --   -10%   -49%
hash   28848/s   496%11% --   -43%
exists 50524/s   944%95%75% --
So in my test exists() is definitely faster.
John
--
use Perl;
program
fulfillment
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response



Re: hash slice/exists vs. grep benchmark weirdness...

2005-01-25 Thread JupiterHost.Net

#!/usr/bin/perl
use warnings;
use strict;
use Benchmark 'cmpthese';
my @k = qw( 1 2 3 4 5 6 );
cmpthese( -10, {
exists  = sub {
my $count = 0;
my %hash;
@hash{ @k } = ();
for my $num ( 1, 3, 5, 7, 9, 11 ) {
$count++ if exists $hash{ $num };
}
return $count;
},
hash= sub {
my $count = 0;
my %hash = map { $_ = 1 } @k;
for my $num ( 1, 3, 5, 7, 9, 11 ) {
$count++ if $hash{ $num };
}
return $count;
},
grep_r  = sub {
my $count = 0;
my @array = @k;
for my $num ( 1, 3, 5, 7, 9, 11 ) {
$count++ if grep /^$num$/, @array;
}
return $count;
},
grep_e  = sub {
my $count = 0;
my @array = @k;
for my $num ( 1, 3, 5, 7, 9, 11 ) {
$count++ if grep $_ == $num, @array;
}
return $count;
},
} );
Produces the result (on my computer):
  Rate grep_r grep_e   hash exists
grep_r  4838/s --   -81%   -83%   -90%
grep_e 25923/s   436% --   -10%   -49%
hash   28848/s   496%11% --   -43%
exists 50524/s   944%95%75% --
So in my test exists() is definitely faster.
Awesome, definately soemthing for me to look into, thanks a bunch John!
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response



Re: hash slice/exists vs. grep benchmark weirdness...

2005-01-25 Thread JupiterHost.Net
 Lawrence Statton wrote:
[snip]
Gotcha, thx
So then can you suggest a method of benchmarking these 2 methods that 
would be more accurate?

I believe John's solution was excellent at illustrating th deficiencies 
in the way I was doing it and supplying a solution  and answering my 
question all at once ;p

I appreciate your input, I'll be more careful of the way I benchmark 
next time :)

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response



hash slice/exists vs. grep benchmark weirdness...

2005-01-24 Thread JupiterHost.Net
In benchmarking some code I've come across something I did not expect:
slice:
use strict;
use warnings;
my @k=qw(1 2 3 4 5 6);
my %n;@[EMAIL PROTECTED] = @k;
print hi if exists $n{1};
print hi if exists $n{3};
print hi if exists $n{5};
print hi if exists $n{7};
print hi if exists $n{9};
print hi if exists $n{11};
grep:
use strict;
use warnings;
my @k=qw(1 2 3 4 5 6);
print hi if grep /^1$/, @k;
print hi if grep /^3$/, @k;
print hi if grep /^5$/, @k;
print hi if grep /^7$/, @k;
print hi if grep /^9$/, @k;
print hi if grep /^11$/, @k;

Benchmark: timing 500 iterations of grep, slice...
  grep: 3.65945 wallclock secs ( 2.33 usr +  0.04 sys =  2.37 CPU) 
@ 2109704.64/s (n=500)
 slice: 2.37966 wallclock secs ( 2.52 usr + -0.01 sys =  2.51 CPU) 
@ 1992031.87/s (n=500)
   Rate slice  grep
slice 1992032/s--   -6%
grep  2109705/s6%--

I would've thought the slice and then use exists would have been 
faster then greping the entire array each time and using regexes when 
you check it. but its consistently faster by an average 6-10%

Any ideas why that might be?
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response



Re: hash slice/exists vs. grep benchmark weirdness...

2005-01-24 Thread Lawrence Statton
 In benchmarking some code I've come across something I did not expect:
 

You have to stop spending so much time playing with all this bogus
benchmarking :)


 slice:
 use strict;
 use warnings;
 my @k=qw(1 2 3 4 5 6);
 my %n;@[EMAIL PROTECTED] = @k;
 print hi if exists $n{1};
 print hi if exists $n{3};
 print hi if exists $n{5};
 print hi if exists $n{7};
 print hi if exists $n{9};
 print hi if exists $n{11};
 
 grep:
 use strict;
 use warnings;
 my @k=qw(1 2 3 4 5 6);
 print hi if grep /^1$/, @k;
 print hi if grep /^3$/, @k;
 print hi if grep /^5$/, @k;
 print hi if grep /^7$/, @k;
 print hi if grep /^9$/, @k;
 print hi if grep /^11$/, @k;
 
 
 
 Benchmark: timing 500 iterations of grep, slice...
grep: 3.65945 wallclock secs ( 2.33 usr +  0.04 sys =  2.37 CPU) 
 @ 2109704.64/s (n=500)
   slice: 2.37966 wallclock secs ( 2.52 usr + -0.01 sys =  2.51 CPU) 
 @ 1992031.87/s (n=500)
 Rate slice  grep
 slice 1992032/s--   -6%
 grep  2109705/s6%--
 
 I would've thought the slice and then use exists would have been 
 faster then greping the entire array each time and using regexes when 
 you check it. but its consistently faster by an average 6-10%
 
 Any ideas why that might be?

Well, first -- you're creating the hash inside the benchmark loop,
which is not particularly light-weight.

Second:  You're using pathologically small lists.  Try running it with
10,000 elements instead of ten.

Third:  Premature optimization is a terrible thing. 

-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
Lawrence Statton - [EMAIL PROTECTED] s/aba/c/g
Computer  software  consists of  only  two  components: ones  and
zeros, in roughly equal proportions.   All that is required is to
sort them into the correct order.

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




How to slice a split directly?

2004-09-23 Thread Siegfried Heintze
This works and does what I want it to:

perl -e '@x = split(\\., a.b.c); print $x[0];'

Why does not this work?
perl -e 'print  @{split(\\., a.b.c)}[0];'

Is there a compact way to take a slice of a split (or other function that
returns an array) without creating a temporary variable?

   Thanks,
  Siegfried


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: How to slice a split directly?

2004-09-23 Thread William Gunther
On Thu, 23 Sep 2004 13:43:08 -0600, Siegfried Heintze
[EMAIL PROTECTED] wrote:
 This works and does what I want it to:
 
 perl -e '@x = split(\\., a.b.c); print $x[0];'
 
 Why does not this work?
 perl -e 'print  @{split(\\., a.b.c)}[0];'

Because split doesn't return an array reference, it returns a list.

print(  (split(/\./, a.b.c))[0]   );

 
 Is there a compact way to take a slice of a split (or other function that
 returns an array) without creating a temporary variable?
 
   Thanks,
  Siegfried
 
 --
 To unsubscribe, e-mail: [EMAIL PROTECTED]
 For additional commands, e-mail: [EMAIL PROTECTED]
 http://learn.perl.org/ http://learn.perl.org/first-response
 
 



-- 
-will 
http://www.wgunther.tk
(the above message is double rot13 encoded for security reasons)

Most Useful Perl Modules
-strict
-warnings
-Devel::DProf
-Benchmark
-B::Deparse
-Data::Dumper
-Clone
-Perl::Tidy
-Beautifier
-DBD::SQLite

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: How to slice a split directly?

2004-09-23 Thread Jenda Krynicky
From: Siegfried Heintze [EMAIL PROTECTED]
 This works and does what I want it to:
 
 perl -e '@x = split(\\., a.b.c); print $x[0];'
 
 Why does not this work?
 perl -e 'print  @{split(\\., a.b.c)}[0];'
 
 Is there a compact way to take a slice of a split (or other function
 that returns an array) without creating a temporary variable?

perl -e 'print ((split(\\., a.b.c))[0]);'

It's a bit tricky. The outermost braces belong to print(), the next 
ones enclose the call to split() so that it can be sliced and the 
innermost enclose the parameters for split(). Only the innermost may 
be left out.

This makes the slicing of function result a bit clearer I think:

($hour, $minute, $sec) = (localtime())[2,1,0];

Jenda
= [EMAIL PROTECTED] === http://Jenda.Krynicky.cz =
When it comes to wine, women and song, wizards are allowed 
to get drunk and croon as much as they like.
-- Terry Pratchett in Sourcery


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: How to slice a split directly?

2004-09-23 Thread Wiggins d Anconia
 This works and does what I want it to:
 
 perl -e '@x = split(\\., a.b.c); print $x[0];'
 
 Why does not this work?
 perl -e 'print  @{split(\\., a.b.c)}[0];'
 
 Is there a compact way to take a slice of a split (or other function that
 returns an array) without creating a temporary variable?
 
Thanks,
   Siegfried
 

Sometimes when working out this kind of detail it is helpful to make a
full script and activate strict/warnings. In the above case you get the
following,

 perl -Mstrict -w -e 'print  @{split(\\., a.b.c)}[0];'
Use of implicit split to @_ is deprecated at -e line 1.
Can't use string (3) as an ARRAY ref while strict refs in use at -e
line 1.

Essentially Csplit returns a list, the construct C@{ } is a way to
slice into a hash, which you don't have. So you need to slice into a
list, which in this case is done like,

perl -Mstrict -w -e 'print  ((split(\\., a.b.c))[0]);'

Notice the extra set of parens, otherwise you get a syntax error because
Cprint would otherwise use the first set as an argument list.

HTH,

http://danconia.org

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




Re: How to slice a split directly?

2004-09-23 Thread Jenda Krynicky
From: Wiggins d Anconia [EMAIL PROTECTED]
  This works and does what I want it to:
  
  perl -e '@x = split(\\., a.b.c); print $x[0];'
  
  Why does not this work?
  perl -e 'print  @{split(\\., a.b.c)}[0];'
  
  Is there a compact way to take a slice of a split (or other function
  that returns an array) without creating a temporary variable?
  
 Thanks,
Siegfried
  
 
 Sometimes when working out this kind of detail it is helpful to make a
 full script and activate strict/warnings. In the above case you get
 the following,
 
  perl -Mstrict -w -e 'print  @{split(\\., a.b.c)}[0];'
 Use of implicit split to @_ is deprecated at -e line 1.
 Can't use string (3) as an ARRAY ref while strict refs in use at
 -e line 1.
 
 Essentially Csplit returns a list, the construct C@{ } is a way to
 slice into a hash, which you don't have. 

There'd have to be a name of a variable between the @ and the opening 
curly brace for that to be a hash slice. This way its an array 
dereference:

@arr = (1,2,3);
$rArr = [EMAIL PROTECTED];
@other = @{$rArr};

Of course in this case you do not need the braces.

You'd use the @{} if the thing you need to dereference is more 
complex, for example if you need to dereference a function result.

So
print join(', ', @{function('returning', 'arrayref')});
would be correct, just like
print join(', ', @{function('returning', 'arrayref')}[1,2,4,7]);

If you'd want just one item from the referenced array you would of 
course use ${}[] instead:

print ${function('returning', 'arrayref')}[2];

In this case the function doesn't return a reference, but a list so 
there is no point in trying to dereference anything :-)

This is where the Can't use string (3) as an ARRAY ref while 
strict refs in use at -e line 1. message comes from. The split() 
is evaluated in scalar context and thus returns the number of 
elements found in the string. And then the code tries to do this:

perl -e 'print  @{3}[0];'

Jenda
= [EMAIL PROTECTED] === http://Jenda.Krynicky.cz =
When it comes to wine, women and song, wizards are allowed 
to get drunk and croon as much as they like.
-- Terry Pratchett in Sourcery


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/ http://learn.perl.org/first-response




slice and dice them

2003-09-30 Thread SilverFox
can anyone tell me how I can remove the period at the end of each line 
below??

.
.
.
.



-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]



Re: slice and dice them

2003-09-30 Thread James Edward Gray II
On Monday, September 29, 2003, at 10:53  AM, SilverFox wrote:

can anyone tell me how I can remove the period at the end of each line
below??
Sure.  Place your cursor at the end of each line in turn and push the 
backspace (or similar key) once...  Oh, did you mean in Perl?  ;)

What part are you stuck on, reading them, altering them or writing them 
out?  If I give you this hint, does it help?

s/\.$//

If not, send us some more details to work with and we'll do better.

James

.
.
.
.


--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]


--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]


RE: slice and dice them

2003-09-30 Thread Wiggins d'Anconia


On Mon, 29 Sep 2003 11:53:16 -0400, SilverFox [EMAIL PROTECTED] wrote:

 can anyone tell me how I can remove the period at the end of each line 
 below??
 
 .
 .
 .
 .
 

Let's see if I can start a flame war ;-)...

perldoc -f chop

http://danconia.org

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]



Re: slice indexing

2003-01-13 Thread Bryan Harris


 I need to slice an array such that it gives me the first through the 4th to
 last in a variable length array.  I thought I could just do:
 
   @comments[0..-4]
 
 but Perl seems to choke on this.  It's perfectly okay with a slice using two
 negative #s:
 
   @comments[-2..-4]
 
 Anyone know why it doesn't like 0..-4?
 
 The first number HAS to be less then the second number so @array[-4..4]
 and @array[-10..-4] are valid but @comments[0..-4] and @comments[-2..-4]
 are not.  For your original question use:
 
 @comments[0..$#comments-4]


Thanks, John and Rob!

- B 


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]




slice indexing

2003-01-12 Thread Bryan Harris

I need to slice an array such that it gives me the first through the 4th to
last in a variable length array.  I thought I could just do:

  @comments[0..-4]

but Perl seems to choke on this.  It's perfectly okay with a slice using two
negative #s:

  @comments[-2..-4]

Anyone know why it doesn't like 0..-4?

TIA.

- B


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]




Re: slice indexing

2003-01-12 Thread John W. Krahn
Bryan Harris wrote:
 
 I need to slice an array such that it gives me the first through the 4th to
 last in a variable length array.  I thought I could just do:
 
   @comments[0..-4]
 
 but Perl seems to choke on this.  It's perfectly okay with a slice using two
 negative #s:
 
   @comments[-2..-4]
 
 Anyone know why it doesn't like 0..-4?


The first number HAS to be less then the second number so @array[-4..4]
and @array[-10..-4] are valid but @comments[0..-4] and @comments[-2..-4]
are not.  For your original question use:

@comments[0..$#comments-4]


John
-- 
use Perl;
program
fulfillment

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]




Re: slice indexing

2003-01-12 Thread Rob Dixon

Rob Dixon [EMAIL PROTECTED] wrote in message
news:[EMAIL PROTECTED]...
 Hi Bryan

 Bryan Harris [EMAIL PROTECTED] wrote in message
 [EMAIL PROTECTED]">news:[EMAIL PROTECTED]...
 
  I need to slice an array such that it gives me the first through the 4th
 to
  last in a variable length array.  I thought I could just do:
 
@comments[0..-4]
 
  but Perl seems to choke on this.  It's perfectly okay with a slice using
 two
  negative #s:
 
@comments[-2..-4]
 
  Anyone know why it doesn't like 0..-4?

 You're using the range operator '..' to generate a list of indices for the
 slice. This operator always counts upwards, so if the first operand is
 greater than the second it will return an empty list.  -2 .. -4 is the
same
 as (-2, -3, -4), but 0 .. -4 is ().

What nonsense!

-2 .. -4 is ()
-4 .. -2 is (-4, -3, -2)

/R




-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]




slice indexing

2003-01-12 Thread Bryan Harris

I need to slice an array such that it gives me the first through the 4th to
last in a variable length array.  I thought I could just do:

  @comments[0..-4]

but Perl seems to choke on this.  It's perfectly okay with a slice using two
negative #s:

  @comments[-2..-4]

Anyone know why it doesn't like 0..-4?

TIA.

- B


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]




RE: Obtaining a slice of unique values from an array

2002-07-01 Thread Shishir K. Singh


on Sun, 30 Jun 2002 12:08:23 GMT, Dan Fish wrote:

 What is the most efficient (or at least AN efficient :-) way of
 obtaining a slice from an array wherein the slice contains only
 unique values found in the array?

See
   perldoc -q duplicate

-- 
felix
This is the example d cited in perldoc -q duplicate
d)  A way to do (b) without any loops or greps:

undef %saw;
@saw{@in} = ();
@out = sort keys %saw;  # remove sort if undesired

I am a bit confused about this example ?? 

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]




Obtaining a slice of unique values from an array

2002-06-30 Thread Dan Fish

What is the most efficient (or at least AN efficient :-) way of obtaining a
slice from an array wherein the slice contains only unique values found in
the array?

I.E.
if @array = (1,3,5,5,3,5,2,1)  then @slice = (1,3,5,2)

Thanks,
-Dan



-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]




array slice syntax

2001-11-03 Thread Thomas Hofer

Hi!

As a perl beginner, I have a silly question about 
array-slices-syntax:

That's clear:

perl -e '@a=(a,b,c);print @a[1..2]\n'
== b c

perl -e '@a=(a,b,c);print $a[1]\n'
== b

But why does $array[range] always give the first array-entry?

perl -e '@a=(a,b,c);print $a[1..2]\n'
== a

(OK, maybe it's useless, but I'd like to understand...)

Thomas.


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]




Re: array slice syntax

2001-11-03 Thread Paul Johnson

On Sat, Nov 03, 2001 at 05:49:37PM +0100, Thomas Hofer wrote:
 Hi!
 
 As a perl beginner, I have a silly question about 
 array-slices-syntax:
 
 That's clear:
 
 perl -e '@a=(a,b,c);print @a[1..2]\n'
 == b c
 
 perl -e '@a=(a,b,c);print $a[1]\n'
 == b
 
 But why does $array[range] always give the first array-entry?
 
 perl -e '@a=(a,b,c);print $a[1..2]\n'
 == a
 
 (OK, maybe it's useless, but I'd like to understand...)

Really?  OK, then :-)

You are using .. in a scalar context.  This is totally different to
using it in an array context.  In scalar context it is the bistable
operator which returns false while its first operand is false, then true
until its second operand is true.  Read more in perlop.

When either operand to .. is a constant, which would otherwise not make
sense, the operand is compared to $. - the number of the line currently
being read.

So, for you the .. operator is returning false, which is converted to 0.

If you want to see what .. is returning, run this:

$ echo 1\n2\n3\n4\n5\n6 | perl -ne 'print , scalar(3..5), \n'


1
2
3E0


These return values are guaranteed.

-- 
Paul Johnson - [EMAIL PROTECTED]
http://www.pjcj.net

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]




create hash slice from hash

2001-10-31 Thread Lisa Neclos

I am attempting to create a hash slice from a hash.  The hash is:

%hash =(test1 = test10,
   test2 = test12 ,
  test3 = test13)

I want the slice to include only the keys test1 and test3.  How can I
accomplish this?


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]




Re: create hash slice from hash

2001-10-31 Thread Curtis Poe

--- Lisa Neclos [EMAIL PROTECTED] wrote:
 I am attempting to create a hash slice from a hash.  The hash is:
 
 %hash =(test1 = test10,
test2 = test12 ,
   test3 = test13)
 
 I want the slice to include only the keys test1 and test3.  How can I
 accomplish this?

Lisa,

my @results = @hash{ qw/ test1 test3 / };

Cheers,
Curtis Ovid Poe

=
Senior Programmer
Onsite! Technology (http://www.onsitetech.com/)
Ovid on http://www.perlmonks.org/

__
Do You Yahoo!?
Make a great connection at Yahoo! Personals.
http://personals.yahoo.com

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]




Re: create hash slice from hash

2001-10-31 Thread Daniel Gardner

LN I am attempting to create a hash slice from a hash.  The hash is:

LN %hash =(test1 = test10,
LNtest2 = test12 ,
LN   test3 = test13)

LN I want the slice to include only the keys test1 and test3.  How can I
LN accomplish this?

you could use map:

  my %new_hash = map { $_ = $hash{$_} } qw(test1 test2);

map is a really useful function...

hth,
daniel


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]




array slice question

2001-06-26 Thread Bradford Ritchie

Hi,

I have an unnamed array which I created from splitting up a colon separated string:

  $_ = 0th:1st:2nd:3rd:4th:5th:6th:7th:Some random text: might have :colons: or 
might not
  print ((split /:/)[1,6,8]);  

...but I really need to print everything after the 8th element.  If the array were 
named, I could do something like this:
  
@arr = split(/:/);
print @arr[1,6,8..$#arr]);

... and this would include everything after the 8th array element.  I know that -1 
should start from the end of the array, but specifying [1,6,8..-1] doesn't work.

I didn't see anything in perldata about it so I'm hoping someone has a solution. 

Thanks.
-- Brad




RE: array slice question

2001-06-26 Thread Stephen Nelson

Well, if you're OK with printing the colons in the last field, you could
simply say:

print ( ( split(/:/, $_, 9) )[1,6,8] );

Since that'll absorb all of the ending fields into the ninth (from zero, so
index 8) field. That would be the correct thing to do if the colons in the
ending field are not field delimiters, but just part of the text.
Other than that, you may need to bite the bullet and name the array.

 -Original Message-
 From: Bradford Ritchie [mailto:[EMAIL PROTECTED]]
 Sent: Tuesday, June 26, 2001 1:46 PM
 To: [EMAIL PROTECTED]
 Subject: array slice question


 Hi,

 I have an unnamed array which I created from splitting up a colon
 separated string:

   $_ = 0th:1st:2nd:3rd:4th:5th:6th:7th:Some random text:
 might have :colons: or might not
   print ((split /:/)[1,6,8]);

 ...but I really need to print everything after the 8th element.
 If the array were named, I could do something like this:

 @arr = split(/:/);
 print @arr[1,6,8..$#arr]);

 ... and this would include everything after the 8th array
 element.  I know that -1 should start from the end of the array,
 but specifying [1,6,8..-1] doesn't work.

 I didn't see anything in perldata about it so I'm hoping someone
 has a solution.

 Thanks.
 -- Brad






Re: array slice question

2001-06-26 Thread dave hoover

Bradford wrote:

 Hi,
 
 I have an unnamed array which I created from
 splitting up a colon separated string:
 
   $_ = 0th:1st:2nd:3rd:4th:5th:6th:7th:Some
 random text: might have :colons: or might not
   print ((split /:/)[1,6,8]);  
 
 ...but I really need to print everything after the
 8th element.  If the array were named, I could do
 something like this:
   
 @arr = split(/:/);
 print @arr[1,6,8..$#arr]);
 
 ... and this would include everything after the 8th
 array element.  I know that -1 should start from the
 end of the array, but specifying [1,6,8..-1] doesn't
 work.
 
 I didn't see anything in perldata about it so I'm
 hoping someone has a solution. 
 
 Thanks.
 -- Brad

Brad,

I can't figure it out either.  Below is a link to a
discussion that mirrors your predicament.  I don't
have time to read it right now, but maybe it will shed
some light on the subject for you.

http://groups.google.com/groups?hl=ensafe=offth=94cd69e466afd840,11start=0ic=1



=
Dave Hoover
Twice blessed is help unlooked for. --Tolkien
http://www.redsquirreldesign.com/dave

__
Do You Yahoo!?
Get personalized email addresses from Yahoo! Mail
http://personal.mail.yahoo.com/



Re: array slice question

2001-06-26 Thread royce . wells


 [1,6,8..-1]

in this case - is seen as a metacharacter inside the character class and
is not seen as -1









Hi,
I have an unnamed array which I created from splitting up a colon separated
string:

  $_ = 0th:1st:2nd:3rd:4th:5th:6th:7th:Some random text: might have
:colons: or might not
  print ((split /:/)[1,6,8]);

...but I really need to print everything after the 8th element.  If the
array were named, I could do something like this:

@arr = split(/:/);
print @arr[1,6,8..$#arr]);

... and this would include everything after the 8th array element.  I know
that -1 should start from the end of the array, but specifying [1,6,8..-1]
doesn't work.

I didn't see anything in perldata about it so I'm hoping someone has a
solution.

Thanks.
-- Brad





The information transmitted is intended only for the person or entity to
which it is addressed and may contain confidential and/or privileged
material. Any review, retransmission, dissemination or other use of, or
taking of any action in reliance upon, this information by persons or
entities other than the intended recipient is prohibited. If you received
this in error, please contact the sender and delete the material from any
computer.




Re: array slice question

2001-06-26 Thread Michael Fowler

On Tue, Jun 26, 2001 at 04:46:24PM -0400, Bradford Ritchie wrote:
 ...but I really need to print everything after the 8th element.  If the
 ...array were named, I could do something like this:
   
 @arr = split(/:/);
 print @arr[1,6,8..$#arr]);

Your asked question was answered well by Stephen Nelson (except it should be
use an array, not name the array, as you are currently not using an
array, but I pedantically digress), so I won't elaborate.

 
 ... and this would include everything after the 8th array element.  I know
 ... that -1 should start from the end of the array, but specifying
 ... [1,6,8..-1] doesn't work.

However, this I will elaborate on.  If you think about it you will be able
to tell why a slice of [8..-1] doesn't work.  The .. operator is not just
used in array slicing, it's a more general range operator.  What sense does
8 .. -1 make outside of the context of a slice?  Count from 8 to.. what,
-1?  That's not what you want from the slice, you want 8 to the end.

There have been several discussions on p5p, and I believe even some perl6
lists, regarding special-casing the .. operator within a slice, but they
usually devolve to disagreement on what it should do outside of a slice.


Michael
--
Administrator  www.shoebox.net
Programmer, System Administrator   www.gallanttech.com
--



  1   2   >