[23221] in Perl-Users-Digest
Perl-Users Digest, Issue: 5442 Volume: 10
daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Thu Sep 4 18:05:42 2003
Date: Thu, 4 Sep 2003 15:05:08 -0700 (PDT)
From: Perl-Users Digest <Perl-Users-Request@ruby.OCE.ORST.EDU>
To: Perl-Users@ruby.OCE.ORST.EDU (Perl-Users Digest)
Perl-Users Digest Thu, 4 Sep 2003 Volume: 10 Number: 5442
Today's topics:
Re: [newbie] list elements <minceme@start.no>
Re: Arbitrarily Complex Data Structure (JR)
Re: Arbitrarily Complex Data Structure (JR)
Is there a $. equivalent for output? <postmaster@castleamber.com>
Re: Looping scalar and regex'ing it <michael.p.broida@boeing.com>
Re: Looping scalar and regex'ing it (Tad McClellan)
Memory Analysis after Hanging <notmyrealemail@sonospam.com>
Re: Memory Analysis after Hanging <postmaster@castleamber.com>
Newbie need help with Perl & SNMP <cable.engineer@nospam.blueyonder.co.uk>
removing error meesage when using sctrict <abcd@efg.com>
Re: removing error meesage when using sctrict <postmaster@castleamber.com>
Re: removing error meesage when using sctrict <abcd@efg.com>
Re: Silly push tricks <bkennedy@hmsonline.com>
Re: Silly push tricks <abigail@abigail.nl>
Re: Small string problem <print split /!/"d!a!v!i!d!o!@!p!a!c!i!f!i!e!r!.!c!o!m!\n">
Re: Small string problem (Tad McClellan)
Digest Administrivia (Last modified: 6 Apr 01) (Perl-Users-Digest Admin)
----------------------------------------------------------------------
Date: Thu, 4 Sep 2003 18:39:32 +0000 (UTC)
From: Vlad Tepes <minceme@start.no>
Subject: Re: [newbie] list elements
Message-Id: <bj80t4$qd1$1@troll.powertech.no>
John Bokma
> Vlad Tepes
>> John Bokma
>>> Vlad Tepes
>>>
>>>> You could perhaps use the fact that hashes have unique keys.
>>>> Try building a hash with the values from the array:
>>>>
>>>> map $hash{$_} = 1, @a; # this will be more efficient [...]
>>>
>>> how about
>>>
>>> my %hash;
>>> @hash{@a} = ( "" ) x @a;
>>
>>
>> Why store anything at all? :-)
>>
>> @hash{@a} = ( undef ) x @a;
>
> And what is undef? Is it not stored?
I always thought that an empty string was something, while undef was
nada. I may be wrong. But... with a testfile
my @a = 0..1e5;
my %hash;
## @hash{@a} = ( "" ) x @a;
@hash{@a} = ( undef ) x @a;
$hash{234} = <STDIN>;
I got the following sizes when looking at output from ips(1):
empty strings: 26212 kB
undef values: 20700 kB
Some quick calculations give:
26212 - 20700 = 5512
5512 * 1024 / 1e5 = 56.44288
So setting a hash value to undef at least appears to save about
56 bytes memory compared to storing it as an empty string.
Wether undef actually is anything, I don't know.
If it isn't, then it can't be stored either ... or what?
--
Vlad
------------------------------
Date: 4 Sep 2003 14:10:48 -0700
From: jrolandumuc@yahoo.com (JR)
Subject: Re: Arbitrarily Complex Data Structure
Message-Id: <b386d54b.0309041310.735b7cde@posting.google.com>
Vlad Tepes <minceme@start.no> wrote in message news:<bj7tln$pdr$1@troll.powertech.no>...
> JR <jrolandumuc@yahoo.com> wrote:
>
> >jrolandumuc@yahoo.com (JR) wrote in message news:<b386d54b.0308291231.4ca368cd@posting.google.com>...
> >>Brian McCauley <nobull@mail.com> wrote in message news:<u97k4xen8c.fsf@wcl-l.bham.ac.uk>...
> >>> jrolandumuc@yahoo.com (JR) writes:
> >>>
> >>>> Hi. Is it possible to create a subroutine to handle an arbitrarily
> >>>> complex data structure (for my purposes, complex only refers to hashes
> >>>> and arrays)?
>
> I just palyed some small with tarversing. Maybe yo like to have a loko:
>
> sub processitem($) {
> my $indent = shift;
> my $item = shift || $_;
> print "$indent ", " " x $indent, $item, "\n";
> }
>
> sub trav(@); # must declare sub to prototype recurs. func.
>
> sub trav {
> my $i = ref $_[0] ? 0 : 1 + shift; # indentation
> foreach ( @_ ) {
> /HASH/ && do{ trav $i, %$_; next };
> /ARRAY/ && do{ trav $i, @$_; next };
> /CODE/ && do{ trav $i, $_->(); next };
> /REF/ && do{ trav $i, $$_ ; next };
> processitem $i;
> }
> }
>
> trav \%hoh, \\\\\%hah, \%hah, \%heh;
>
> Cherio,
Interesting approach! Your code is maximally succinct. When I passed
it a reference to my ridiculously complex %ds hash, it produced the
below output (I also passed it far less ridiculous hashes and arrays,
and it processed those perfectly). When I added in a line to handle
scalars, it perfectly processed a reference to %ds. I didn't bother
trying to indent, the way you did (I just needed to get the actual raw
data out of the data structure). That was a nice touch.
Prototype mismatch: sub main::trav (@_) vs none at test.pl line 79.
1 hoa
1 SCALAR(0x1aa7848)
1 aoh
1 SCALAR(0x1aa7794)
1 hash1
2 e
2 English
2 r
2 Russian
2 s
2 Spanish
1 norefscalar
1 Hello, World!
1 combo
2 SCALAR(0x1aa8274)
3 SCALAR(0x1aa82a4)
4 SCALAR(0x1aa82d4)
5 SCALAR(0x1aa8310)
1 anon1
2 10
2 11
2 12
2 13
2 14
2 15
2 16
2 17
2 18
2 19
2 20
1 hoh
1 SCALAR(0x1aa8430)
1 scalar1
1 SCALAR(0x1aac2cc)
1 sub1
1 SCALAR(0x1aa8124)
1 aoa
3 0
3 1
3 2
3 3
3 4
3 5
3 6
3 7
3 8
1 layeredstuct
3 hoa_key1
4 hoa_anon1
5 hoa_int_anon1
4 hoa_anon1a
3 hoa_key2
4 hoa_anon2
5 hoa_int_anon2
4 hoa_anon2a
3 hoa_key3
4 hoa_anon3
5 hoa_int_anon3
4 hoa_anon3a
3 SCALAR(0x1aa79f8)
The below code is as succinct I could get it (within reason), for what
I was trying to accomplish. I was a little dissapointed about not
being able to factor this code down a little more, but at least it did
spit out exactly the output that I wanted, for every data structure I
passed it (which is why I bothered putting it into a class). I'll be
able to make it more succinct now, thanks to your code.
Thanks.
JR
---- calling script ----
use lib 'OO_Practice';
use strict;
use TRAVERSE;
## Pass it a reference to the %ds hash from previous message
my $object = TRAVERSE->new(\%ds)->printTree;
---- receiving class ----
package TRAVERSE;
use strict;
### This class recursively traverses any arbitrarily deep data
structure that
### has any number of references to hashes, arrays, scalars or
subroutines;
### other types are tagged as exceptions. The data structure must be
passed
### as a reference.
my $iteration_count = 0;
my $obj;
sub new {
my $class = shift;
$class = ref($class) || $class;
my $self = [@_];
bless $self, $class;
$self->_extract_reference();
return $self;
}
sub _extract_reference {
my $self = shift;
$self->_traverse(@$self);
}
sub _traverse {
my $arg;
if (!$iteration_count) {
my $self = shift;
$iteration_count++;
$arg = shift;
_traverse($arg);
}
else {
$arg = shift;
}
## Initial argument must be a reference.
## If argument is passed a reference data structure,
## but not as a reference, this block will be circumvented,
## and the passed reference may not be completely _traversed.
if ($iteration_count == 1 && ref($arg) ne 'REF' &&
ref($arg) ne 'HASH' &&
ref($arg) ne 'ARRAY' &&
ref($arg) ne 'CODE' &&
ref($arg) ne 'SCALAR') {
die "Data structure must be passed as a reference.\n";
}
## Handle references to a reference
if (ref($arg) eq 'REF') {
## Try hash
eval { %$arg; };
_traverse(%$arg) if (!$@);
## Try array
eval { @$arg; };
_traverse(@$arg) if (!$@);
## Try scalar
eval { $$arg; };
_traverse($$arg) if (!$@);
## Try code
eval { &$arg; };
_traverse(&$arg) if (!$@);
}
elsif (ref($arg) eq 'HASH') {
for (%$arg) {
ref($_) eq 'HASH' || ref($_) eq 'ARRAY' || ref($_) eq
'SCALAR' ||
ref($_) eq 'CODE' ||
ref($_) eq 'REF' ? _traverse($_) : push @{$obj->{tree}}, $_,
"\n";
}
}
elsif (ref($arg) eq 'ARRAY') {
for (@$arg) {
ref($_) eq 'HASH' || ref($_) eq 'ARRAY' || ref($_) eq
'SCALAR' ||
ref($_) eq 'CODE' ||
ref($_) eq 'REF' ? _traverse($_) : push @{$obj->{tree}}, $_,
"\n";
}
}
elsif (ref($arg) eq 'SCALAR') {
ref($$arg) eq 'HASH' || ref($$arg) eq 'ARRAY' || ref($$arg) eq
'SCALAR' ||
ref($$arg) eq 'CODE' || ref($$arg) eq 'REF' ? _traverse($$arg) :
push @{$obj->{tree}}, $$arg, "\n";
}
elsif (ref($arg) eq 'CODE') {
ref(&$arg()) eq 'HASH' || ref(&$arg()) eq 'ARRAY' ||
ref(&$arg()) eq 'SCALAR'||
ref(&$arg()) eq 'CODE' ||
ref(&$arg()) eq 'REF' ? _traverse(&$arg) : push @{$obj->{tree}},
&$arg();
}
else {
push @{$obj->{tree}}, warn "EXCEPTION: $arg\n";
}
}
sub printTree {
my $self = shift;
print "$_" for @{$obj->{tree}};
}
1;
------------------------------
Date: 4 Sep 2003 14:52:34 -0700
From: jrolandumuc@yahoo.com (JR)
Subject: Re: Arbitrarily Complex Data Structure
Message-Id: <b386d54b.0309041352.7f4d5117@posting.google.com>
Vlad Tepes <minceme@start.no> wrote in message news:<bj7tln$pdr$1@troll.powertech.no>...
> JR <jrolandumuc@yahoo.com> wrote:
>
> >jrolandumuc@yahoo.com (JR) wrote in message news:<b386d54b.0308291231.4ca368cd@posting.google.com>...
> >>Brian McCauley <nobull@mail.com> wrote in message news:<u97k4xen8c.fsf@wcl-l.bham.ac.uk>...
> >>> jrolandumuc@yahoo.com (JR) writes:
> >>>
> >>>> Hi. Is it possible to create a subroutine to handle an arbitrarily
> >>>> complex data structure (for my purposes, complex only refers to hashes
> >>>> and arrays)?
>
> I just palyed some small with tarversing. Maybe yo like to have a loko:
>
> sub processitem($) {
> my $indent = shift;
> my $item = shift || $_;
> print "$indent ", " " x $indent, $item, "\n";
> }
>
> sub trav(@); # must declare sub to prototype recurs. func.
>
> sub trav {
> my $i = ref $_[0] ? 0 : 1 + shift; # indentation
> foreach ( @_ ) {
> /HASH/ && do{ trav $i, %$_; next };
> /ARRAY/ && do{ trav $i, @$_; next };
> /CODE/ && do{ trav $i, $_->(); next };
> /REF/ && do{ trav $i, $$_ ; next };
> processitem $i;
> }
> }
>
> trav \%hoh, \\\\\%hah, \%hah, \%heh;
>
> Cherio,
With your technique, I was able to significantly factor-down my code
(the one key component I was forgetting is that a reference to a
reference is always dereferenced as a scalar---that's why I had so
many unnecessary evals in my first script). I also noticed that the
ref has to be tested for in the for loop--using regex can lead to some
mistakes. Anyway, below is the much more succinct code for my class
and calling script. Thanks, Vlad.
---calling script---
use lib 'OO_Practice';
use strict;
use warnings;
use diagnostics;
use TRAVERSE;
my $object = TRAVERSE->new(\%ds);
---receiving class (not really OO, just uses an OO interface)---
package TRAVERSE;
use strict;
my $obj;
sub new {
my $class = shift;
$class = ref($class) || $class;
my $data = \@_;
_trav(@$data);
print "$_" for @{$obj->{tree}};
my $self = [@{$obj->{tree}}];
bless $self, $class;
return $self;
}
sub _trav {
my $arg = ref $_[0];
for (@_) {
if (!ref($_)) {print "$_\n"; next;}
S: {
if (ref($_) eq 'REF') {_trav($$_); last S;}
if (ref($_) eq 'HASH') {_trav(%$_); last S;}
if (ref($_) eq 'ARRAY') {_trav(@$_); last S;}
if (ref($_) eq 'SCALAR') {_trav($$_); last S;}
if (ref($_) eq 'CODE') {_trav(&$arg()); last S;}
push @{$obj->{tree}}, warn "EXCEPTION: $_\n";
};
}
}
1;
That's it!
------------------------------
Date: Thu, 04 Sep 2003 23:55:59 +0200
From: John Bokma <postmaster@castleamber.com>
Subject: Is there a $. equivalent for output?
Message-Id: <3f57b552$0$192$58c7af7e@news.kabelfoon.nl>
Is there a $. equivalent for output, ie. current linenumber of output when I
print FILE "line\n";
--
Kind regards, feel free to mail: mail(at)johnbokma.com (or reply)
virtual home: http://johnbokma.com/ ICQ: 218175426
John web site hints: http://johnbokma.com/websitedesign/
------------------------------
Date: Thu, 4 Sep 2003 18:26:23 GMT
From: "Michael P. Broida" <michael.p.broida@boeing.com>
Subject: Re: Looping scalar and regex'ing it
Message-Id: <3F5783CF.FDB9EA33@boeing.com>
Moltar wrote:
>
> Hmm.. I was actually thinking of looping. Because I need to do other stuff with it later.
NOTE: I haven't tested this! But it fits the docs
and posts here that I've read. Posted just to
give you some ideas.
You can use the "/g" on the string match in a loop with a scalar
result instead of an array. Each time you do the string match,
it will remember the previous point and work from there.
In other words, something like: (AGAIN: UNTESTED!)
while ($onematch = $string =~ /wha(tev)er/g)
{
work with $onematch
}
(Or drop the "$onematch =" and work with $1.)
When there are no further matches in the string, it will return
undef and exit the loop (unless I've screwed it up). Anyway,
that fits the docs for "/g" with a scalar result.
NOTE: Doing other regex work inside the loop will (I'm pretty sure)
screw it up: it will lose its place in $string. Or I could be
wrong on that, too. Well, maybe this helps a tiny bit. :)
Mike
------------------------------
Date: Thu, 4 Sep 2003 15:55:50 -0500
From: tadmc@augustmail.com (Tad McClellan)
Subject: Re: Looping scalar and regex'ing it
Message-Id: <slrnblf9mm.1up.tadmc@magna.augustmail.com>
Michael P. Broida <michael.p.broida@boeing.com> wrote:
> Moltar wrote:
>>
>> Hmm.. I was actually thinking of looping. Because I need to do other stuff with it later.
> You can use the "/g" on the string match in a loop with a scalar
> result instead of an array. Each time you do the string match,
^^^^^^^^^^^^^^^^^^^
( instead of a _list_ )
> it will remember the previous point and work from there.
and the pos() function will tell you where it left off.
> NOTE: Doing other regex work inside the loop will (I'm pretty sure)
> screw it up: it will lose its place in $string. Or I could be
> wrong on that, too.
You can do other pattern matching against _other_ strings with
no problem.
If you do mattern matching with $string though, then the match
position is _supposed to_ move.
The position info resides with the string being matched against,
rather than with the pattern to be matched.
You can use the \G anchor in all of the patterns that match
against $string to force it to start off where the last
one left off.
--
Tad McClellan SGML consulting
tadmc@augustmail.com Perl programming
Fort Worth, Texas
------------------------------
Date: Thu, 04 Sep 2003 20:51:40 +0100
From: Mark <notmyrealemail@sonospam.com>
Subject: Memory Analysis after Hanging
Message-Id: <1t5flvc79nk8ugufen2m2bp1fk1sud0ni6@4ax.com>
We are running a script to load text files into 8 MySQL tables. Each
text file contains tens of thousands of lines, each line containing
pipe seperated values. The script loops until all 8 tables are loaded
and it has worked fine till now. For a new client we must upload
nearly 10mb of data and our script gets threequarters of the way
through the file and then just hangs. Our ISP confirms that the script
has run out of memory.
Does anyone know of any diagnostic tools that can help us to isolate
the component(s) that are not being cleared from memory? As we use a
shared hosting account through an ISP we don't have direct access to
the server. I have been looking at the Devel::peek module but this
seems to be for mod_perl only.
The server has produced a core file, but we don't have telnet access
to our shared server account. Are there any suitable readers that will
run in windows?
What is meant by including debug data in the appliciation in order to
make the core file more readable?
Is there an alternative way to solving this problem, e.g. if for each
text file we opened a piped process using another perl script would
memory be returned for further use once the piped process had
terminated?
Many thanks in advance,
Mark
------------------------------
Date: Thu, 04 Sep 2003 21:56:21 +0200
From: John Bokma <postmaster@castleamber.com>
Subject: Re: Memory Analysis after Hanging
Message-Id: <3f579949$0$199$58c7af7e@news.kabelfoon.nl>
Mark wrote:
> We are running a script to load text files into 8 MySQL tables. Each
> text file contains tens of thousands of lines, each line containing
> pipe seperated values. The script loops until all 8 tables are loaded
> and it has worked fine till now. For a new client we must upload
> nearly 10mb of data and our script gets threequarters of the way
> through the file and then just hangs. Our ISP confirms that the script
> has run out of memory.
Do you slurp the file or read it line by line? Do you store the info in
each line or insert it on the fly?
> Is there an alternative way to solving this problem, e.g. if for each
post the script, unless it is huge. In that case provide us with a link.
You can mail me the script if you want to keep it confidential but then
I want a book in return :-D.
--
Kind regards, feel free to mail: mail(at)johnbokma.com (or reply)
virtual home: http://johnbokma.com/ ICQ: 218175426
John web site hints: http://johnbokma.com/websitedesign/
------------------------------
Date: Thu, 04 Sep 2003 20:47:14 GMT
From: stewart dunn <cable.engineer@nospam.blueyonder.co.uk>
Subject: Newbie need help with Perl & SNMP
Message-Id: <ha6flvohbh8eb1tol2k0h2uidaltcl3gk0@4ax.com>
Hi,
We have several large class B subnets of which we wish to poll-4 snmp
variables in total (not Sys Uptime). I'm looking for some sort of script
(based on Perl?) that will take each devices IP address in turn from a
previously composed text/csv file, poll each device in question and
return the results to another text/csv file. This script will have to be
capable of running against >10,000 devices. I can't find anything
commercial that can cope with this scale as they seem to run out of
""puff"" before the run completes. Even a script that could use smaller
list's of IP's that could rest between runs would be good.
Can anybody help?
------------------------------
Date: Thu, 04 Sep 2003 14:59:11 -0500
From: Ben <abcd@efg.com>
Subject: removing error meesage when using sctrict
Message-Id: <bj85ig$gfqai$1@ID-121117.news.uni-berlin.de>
Hi,
I wrote a simple script (45 lines, no functions) that defines some
variables. I decided to "use strict" for a change and it came up with
errors along the following lines:
Global symbol "$ofile" requires explicit package name at ./fileParser.pl
line 43
Is there any way I can remove the error without going through the file
and replacing the variables with $main::variable?
Thanks,
Ben
--
BTW. I can be contacted at Username:newsgroup4.replies.benaltw
Domain:xoxy.net
------------------------------
Date: Thu, 04 Sep 2003 22:04:49 +0200
From: John Bokma <postmaster@castleamber.com>
Subject: Re: removing error meesage when using sctrict
Message-Id: <3f579b44$0$199$58c7af7e@news.kabelfoon.nl>
Ben wrote:
> Hi,
>
> I wrote a simple script (45 lines, no functions) that defines some
> variables. I decided to "use strict" for a change and it came up with
> errors along the following lines:
>
> Global symbol "$ofile" requires explicit package name at ./fileParser.pl
> line 43
my $ofile;
--
Kind regards, feel free to mail: mail(at)johnbokma.com (or reply)
virtual home: http://johnbokma.com/ ICQ: 218175426
John web site hints: http://johnbokma.com/websitedesign/
------------------------------
Date: Thu, 04 Sep 2003 15:11:26 -0500
From: Ben <abcd@efg.com>
Subject: Re: removing error meesage when using sctrict
Message-Id: <bj869e$g9un3$1@ID-121117.news.uni-berlin.de>
John Bokma wrote:
>> I wrote a simple script (45 lines, no functions) that defines some
>> variables. I decided to "use strict" for a change and it came up with
>> errors along the following lines:
>>
>> Global symbol "$ofile" requires explicit package name at
>> ./fileParser.pl line 43
>
>
> my $ofile;
Thanks. I had 'my' in there and removed them for some stupid reason.
regards,
Ben
--
BTW. I can be contacted at Username:newsgroup4.replies.benaltw
Domain:xoxy.net
------------------------------
Date: Thu, 4 Sep 2003 16:54:25 -0400
From: "Ben Kennedy" <bkennedy@hmsonline.com>
Subject: Re: Silly push tricks
Message-Id: <Sa-dnYkA3YYfO8qiXTWJjg@giganews.com>
"Abigail" <abigail@abigail.nl> wrote in message
news:slrnblcs06.n3b.abigail@alexandra.abigail.nl...
> Charlton Wilbur (cwilbur@mithril.chromatico.net) wrote on MMMDCLV
> September MCMXCIII in <URL:news:878yp57f6r.fsf@mithril.chromatico.net>:
> :) >>>>> "A" == Abigail <abigail@abigail.nl> writes:
> :)
> :) [using map in void context]
> :)
> :) A> Poor style? Why?
> :)
> :) Because
> :)
> :) map { fn($_) } @list;
> :)
> :) and
> :) fn ($_) foreach @list;
> :)
> :) (where fn is a function with side-effects) do the same thing, but the
> :) latter is better style.
>
> Beside that they are different (the context in which fn is called
> differs) you don't give *any* argument why one is better style
> than the other.
Using map() or grep() like this obfuscates the intent of the code. It
certianly works, but it is not the most straightforward way of expressing
the notion of "do one thing for each element in this list" - foreach()
clearly is. Whether or not this is "poor style" depends on your point of
view, of course. I prefer code to be as unambiguous as possible, as this
makes it is easier to read, understand, and maintain. Using functions and
modifers as described in the documentation and FAQ tend to do this for me.
"Bad style" is clearly in the eye of the beholder, as someone could be
perfectly comfortable with using map to iterate over loops and would not
experience any loss in comprehension... but I'd guess that most seasoned
Perl programmers would blink once or twice.
--Ben Kennedy
------------------------------
Date: 04 Sep 2003 21:11:36 GMT
From: Abigail <abigail@abigail.nl>
Subject: Re: Silly push tricks
Message-Id: <slrnblfak7.ggi.abigail@alexandra.abigail.nl>
Ben Kennedy (bkennedy@hmsonline.com) wrote on MMMDCLVI September MCMXCIII
in <URL:news:Sa-dnYkA3YYfO8qiXTWJjg@giganews.com>:
``
`` Using map() or grep() like this obfuscates the intent of the code. It
`` certianly works, but it is not the most straightforward way of expressing
`` the notion of "do one thing for each element in this list" - foreach()
`` clearly is. Whether or not this is "poor style" depends on your point of
`` view, of course. I prefer code to be as unambiguous as possible, as this
`` makes it is easier to read, understand, and maintain. Using functions and
`` modifers as described in the documentation and FAQ tend to do this for me.
`` "Bad style" is clearly in the eye of the beholder, as someone could be
`` perfectly comfortable with using map to iterate over loops and would not
`` experience any loss in comprehension... but I'd guess that most seasoned
`` Perl programmers would blink once or twice.
I think I'm a seasoned Perl programmer, and I see nothing wrong with
'map { } LIST' in void context. I find the argument 'it is not the most
straightforward way of expressing the notion of "do one thing for each
element in this list"' very subjective. Perhaps if you only have limited
exposure to programming languages, and only know about C and Java,
"map" as a means of mapping a function over a set is alien concept. But
if you have a different heritage, you may see things otherwise. I find
"map" in many cases more natural than "foreach", it fits more with the
programming metholodogies I was taught at University, and with languages
I've used before I learned Perl.
As for code being as "unambiguous as possible", well, Python is thataway.
Perl is all about "there is more than one way of doing it".
Abigail
--
@_=map{[$!++=>$_^$/]}split$²=>"\@\x7Fy~*kde~box*Zoxf*Bkiaox";$\="\r";
$|=++$*;do{($#=>$=)=(rand@_=>rand@_);@_[$#,$=]=@_[$=,$#]}for($*..@_);
for$:($|..@_-$|){for($|..@_-$:){@_[$_-$|,$_]=@_[$_=>$_-$*]if$_[$_][$¼
]<$_[$_-$*][$®];print+map{$_->[$|]}@_;select$·,$°,$½,"$[.$|"}}print$/
------------------------------
Date: Thu, 4 Sep 2003 11:10:29 -0700
From: "David Oswald" <print split /!/"d!a!v!i!d!o!@!p!a!c!i!f!i!e!r!.!c!o!m!\n">
Subject: Re: Small string problem
Message-Id: <vlf00c4l8qsc35@corp.supernews.com>
"PeterT" <kraut@ukrmdotnet.cut> wrote in message
news:bj7ir8$gq$1@news.ox.ac.uk...
> I'm trying to extract the numerical part and the letter part of a short
> string.
>
> i.e.
>
> $mix = "6KL" --> $num = "6" and $let = "KL"
>
> I can't find a way to do it with split, or substr
>
> anybody can give me a clue? ;-)
As your problem expanded with your understanding of how matching works, you
probably came up with the following regexp already, but if not, here it is:
my ( $num, $let ) = $mix =~ m/(\d+)(.+)/;
This tells the regexp engine to match all digits at the beginning of the
string (one or more), and to match everything else (one or more). I make the
assumption that there will always be digits, and there will always be
something following the digits.
Note that this will fail on the following situation: If the string consists
of "1111", you will get 111 as the number and 1 as the remainder. Why?
Because we've told '.' that it has to match something. You could avoid this
by saying .* instead of .+.
------------------------------
Date: Thu, 4 Sep 2003 16:33:39 -0500
From: tadmc@augustmail.com (Tad McClellan)
Subject: Re: Small string problem
Message-Id: <slrnblfbtj.1up.tadmc@magna.augustmail.com>
Ryan Shondell <shondell@cis.ohio-state.edu> wrote:
> "Christian Caron" <nospam@nospam.org> writes:
>> This would work:
>>
>> ($let = $mix) =~ s/^(\d+)//;
>> $num = $1;
>>
>> It would catch any numbers (if they are at the beginning of the string) and
>> put them in $1
^^^^^^^^^^^^^^
But only when the s/// _succeeded_.
>> (later assigned to $num), and also remove these numbers from
>> $let.
> this solution
> could have some problems if you have previously put something in $1,
It has the same problem if you have _not_ previously put something
in $1, its value will just be undef.
> but there are no numbers in your string.
Right.
What matters is not what is in $1.
What matters is whether the match succeeded or not.
It it failed, $1 will have "stale" contents from some earlier
(successful) match, or undef.
--
Tad McClellan SGML consulting
tadmc@augustmail.com Perl programming
Fort Worth, Texas
------------------------------
Date: 6 Apr 2001 21:33:47 GMT (Last modified)
From: Perl-Users-Request@ruby.oce.orst.edu (Perl-Users-Digest Admin)
Subject: Digest Administrivia (Last modified: 6 Apr 01)
Message-Id: <null>
Administrivia:
The Perl-Users Digest is a retransmission of the USENET newsgroup
comp.lang.perl.misc. For subscription or unsubscription requests, send
the single line:
subscribe perl-users
or:
unsubscribe perl-users
to almanac@ruby.oce.orst.edu.
To submit articles to comp.lang.perl.announce, send your article to
clpa@perl.com.
To request back copies (available for a week or so), send your request
to almanac@ruby.oce.orst.edu with the command "send perl-users x.y",
where x is the volume number and y is the issue number.
For other requests pertaining to the digest, send mail to
perl-users-request@ruby.oce.orst.edu. Do not waste your time or mine
sending perl questions to the -request address, I don't have time to
answer them even if I did know the answer.
------------------------------
End of Perl-Users Digest V10 Issue 5442
***************************************