[32449] in Perl-Users-Digest
Perl-Users Digest, Issue: 3716 Volume: 11
daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Sat Jun 16 14:09:25 2012
Date: Sat, 16 Jun 2012 11:09:10 -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 Sat, 16 Jun 2012 Volume: 11 Number: 3716
Today's topics:
Re: an effective script for grabbing and putting images <jimsgibson@gmail.com>
Re: an effective script for grabbing and putting images <ben@morrow.me.uk>
Re: an effective script for grabbing and putting images <rweikusat@mssgmbh.com>
Re: an effective script for grabbing and putting images <rweikusat@mssgmbh.com>
Re: an effective script for grabbing and putting images <ben@morrow.me.uk>
Re: an effective script for grabbing and putting images <rweikusat@mssgmbh.com>
Re: an effective script for grabbing and putting images <m@rtij.nl.invlalid>
Re: an effective script for grabbing and putting images <cal@example.invalid>
Re: an effective script for grabbing and putting images <cal@example.invalid>
Re: an effective script for grabbing and putting images <ben@morrow.me.uk>
Learning OOP <rodbass63@gmail.com>
Re: Learning OOP <jimsgibson@gmail.com>
Re: new topic: I call length($<string>) and get number <rweikusat@mssgmbh.com>
Re: new topic: I call length($<string>) and get number (Tim McDaniel)
Re: new topic: I call length($<string>) and get number <ben@morrow.me.uk>
pass array reference <bjlockie@lockie.ca>
Re: pass array reference <rweikusat@mssgmbh.com>
Re: pass array reference <jimsgibson@gmail.com>
Re: pass array reference <rweikusat@mssgmbh.com>
Digest Administrivia (Last modified: 6 Apr 01) (Perl-Users-Digest Admin)
----------------------------------------------------------------------
Date: Fri, 15 Jun 2012 17:10:56 -0700
From: Jim Gibson <jimsgibson@gmail.com>
Subject: Re: an effective script for grabbing and putting images from or to a website
Message-Id: <150620121710565739%jimsgibson@gmail.com>
In article <5c2dnd3ipqJmI0bSnZ2dnUVZ_s6dnZ2d@supernews.com>, Cal
Dershowitz <cal@example.invalid> wrote:
> On 06/15/2012 03:56 PM, Martijn Lievaart wrote:
> > On Wed, 13 Jun 2012 14:45:11 +0100, Ben Morrow wrote:
> >
> >> This provides the additional advantage of following the proper
> >> write-close-rename idiom for making a file available atomically
> >> (probably not important in this case, but it never does any harm).
> >
> > Maybe not important in this case, but a good habit to get into.
>
> There's a second part of the script that I can't quite seem to get
> wrangled. I'll excerpt as opposed to making a full listing:
>
>
> my @files = <$path*>;
>
> my $big_int = 1;
> for my $name (@files) {
> print "name is $name\n";
> $name =~ m/.*\.(w+)/;
You need \w instead of w.
The '.*' would be unnecessary if you anchored the pattern, or if only
one period ever occurred in your file names, and might be faster:
$name =~ m/\.(\w+)$/;
> my $ext = $1;
> print "ext is $ext\n";
>
> }
>
--
Jim Gibson
------------------------------
Date: Sat, 16 Jun 2012 02:20:51 +0100
From: Ben Morrow <ben@morrow.me.uk>
Subject: Re: an effective script for grabbing and putting images from or to a website
Message-Id: <jk3ta9-c5p.ln1@anubis.morrow.me.uk>
Quoth Jim Gibson <jimsgibson@gmail.com>:
> In article <5c2dnd3ipqJmI0bSnZ2dnUVZ_s6dnZ2d@supernews.com>, Cal
> Dershowitz <cal@example.invalid> wrote:
>
> > my @files = <$path*>;
> >
> > my $big_int = 1;
> > for my $name (@files) {
> > print "name is $name\n";
> > $name =~ m/.*\.(w+)/;
>
> You need \w instead of w.
...and, you *also* need to check the match succeeded before you look at
$1:
$name =~ m/.*\.(\w+)/ or die "'$name' has no extension";
otherwise you run the risk of picking up $1 from some entirely other
pattern match. The $N variables are slightly strangely scoped, so this
is a little less likely than it might be, but it can and does happen and
causes *very* strange bugs when it does. Some other action may be more
appropriate that 'die'; perhaps printing a warning and using 'next' to
skip to the next file.
As a general rule it's easier to avoid the $N variables where possible,
and instead use the return value of the match:
my ($ext) = $name =~ m/.*\.(\w+)/;
That way even if the match fails $ext will be undef rather than some
random other value. The brackets around $ext are important: they force
the assignment to occur in list context, so that the match returns a
list of captures rather than a boolean for success or failure.
Ben
------------------------------
Date: Sat, 16 Jun 2012 13:49:09 +0100
From: Rainer Weikusat <rweikusat@mssgmbh.com>
Subject: Re: an effective script for grabbing and putting images from or to a website
Message-Id: <87zk83fmm2.fsf@sapphire.mobileactivedefense.com>
Ben Morrow <ben@morrow.me.uk> writes:
> Quoth Jim Gibson <jimsgibson@gmail.com>:
>> In article <5c2dnd3ipqJmI0bSnZ2dnUVZ_s6dnZ2d@supernews.com>, Cal
>> Dershowitz <cal@example.invalid> wrote:
>>
>> > my @files = <$path*>;
>> >
>> > my $big_int = 1;
>> > for my $name (@files) {
>> > print "name is $name\n";
>> > $name =~ m/.*\.(w+)/;
>>
>> You need \w instead of w.
>
> ...and, you *also* need to check the match succeeded before you look at
> $1:
>
> $name =~ m/.*\.(\w+)/ or die "'$name' has no extension";
>
> otherwise you run the risk of picking up $1 from some entirely other
> pattern match. The $N variables are slightly strangely scoped, so this
> is a little less likely than it might be, but it can and does happen and
> causes *very* strange bugs when it does.
[...]
> As a general rule it's easier to avoid the $N variables where possible,
> and instead use the return value of the match:
What's so difficult with providing information instead of
scaremongering?
According to perlre(1),
The numbered match variables ($1, $2, $3, etc.)
[...]
are all dynamically scoped until the end of the
enclosing block or until the next successful match,
Practically, this means the simple way to use $1 etc correctly is to
avoid using them except if the match supposed to set them was
successful, in this case (assuming that $ext is a hitherto untouched
my variable)
$name =~ m/.*\.(\w+)/ and $ext = $1;
In more complicated cases,
if (<some re match>) {
# $1 etc valid here
}
or
<some re match> && do {
# also here
};
can be used.
------------------------------
Date: Sat, 16 Jun 2012 14:27:15 +0100
From: Rainer Weikusat <rweikusat@mssgmbh.com>
Subject: Re: an effective script for grabbing and putting images from or to a website
Message-Id: <87y5nnl74c.fsf@sapphire.mobileactivedefense.com>
Rainer Weikusat <rweikusat@mssgmbh.com> writes:
[...]
> According to perlre(1),
>
> The numbered match variables ($1, $2, $3, etc.)
>
> [...]
>
> are all dynamically scoped until the end of the
> enclosing block or until the next successful match,
This text could do with an additional explanation: The way 'scoped' is
used here doesn't really make sense. What this means is that $1,
... are always local (like local) to the enclosing block and that
their values always correspond with whatever was or wasn't captured by
the last successful match inside this block. Example demonstrating
most of this:
----------------
$a = 'Hallo';
{
$a =~ /(H)/;
{
$a =~ /(l)(l)/;
print "$1, $2\n";
$a =~ /(x)/;
print "$1, $2\n";
$a =~ /(a)/;
print "$1, $2\n";
}
print "$1, $2\n";
}
print "$1, $2\n";
------------------------------
Date: Sat, 16 Jun 2012 16:52:44 +0100
From: Ben Morrow <ben@morrow.me.uk>
Subject: Re: an effective script for grabbing and putting images from or to a website
Message-Id: <cnmua9-bee1.ln1@anubis.morrow.me.uk>
Quoth Rainer Weikusat <rweikusat@mssgmbh.com>:
> Ben Morrow <ben@morrow.me.uk> writes:
> >
> > ...and, you *also* need to check the match succeeded before you look at
> > $1:
> >
> > $name =~ m/.*\.(\w+)/ or die "'$name' has no extension";
> >
> > otherwise you run the risk of picking up $1 from some entirely other
> > pattern match. The $N variables are slightly strangely scoped, so this
> > is a little less likely than it might be, but it can and does happen and
> > causes *very* strange bugs when it does.
>
> > As a general rule it's easier to avoid the $N variables where possible,
> > and instead use the return value of the match:
>
> What's so difficult with providing information instead of
> scaremongering?
I did. I showed the OP how to use $N correctly, and also provided an
alternative I (at least) find easier to use. Where is the
scaremongering?
> According to perlre(1),
>
> The numbered match variables ($1, $2, $3, etc.)
> [...]
> are all dynamically scoped until the end of the
> enclosing block or until the next successful match,
I omitted that detail, since it was not relevant at that point.
> Practically, this means the simple way to use $1 etc correctly is to
> avoid using them except if the match supposed to set them was
> successful,
...as I said...
> in this case (assuming that $ext is a hitherto untouched
> my variable)
>
> $name =~ m/.*\.(\w+)/ and $ext = $1;
Ugly and crude. Assigning the return value of the match is much cleaner.
> In more complicated cases,
>
> if (<some re match>) {
> # $1 etc valid here
> }
That is a useful construction sometimes, but it's usually clearer for
exceptional flow control ('match failed') to be the branch which diverts
from the normal flow. Hence my suggestion to 'match or die', or
equivalently something like
unless (/.../) {
warn "..."
next;
}
That way the entire block can be ignored as 'error handling' when
skimming through the code.
I find this sub useful for that purpose:
sub wnext {
no warnings "exiting";
warn $_[0];
next;
}
since it allows
/.../ or wnext "no extension on '$file'";
analogously to the standard 'or die' idiom.
> <some re match> && do {
> # also here
> };
God, that's ugly. If you mean 'if', write 'if', and if you mean 'and',
write 'and'.
Ben
------------------------------
Date: Sat, 16 Jun 2012 18:05:43 +0100
From: Rainer Weikusat <rweikusat@mssgmbh.com>
Subject: Re: an effective script for grabbing and putting images from or to a website
Message-Id: <87y5nnqja0.fsf@sapphire.mobileactivedefense.com>
Ben Morrow <ben@morrow.me.uk> writes:
> Quoth Rainer Weikusat <rweikusat@mssgmbh.com>:
>> Ben Morrow <ben@morrow.me.uk> writes:
>> >
>> > ...and, you *also* need to check the match succeeded before you look at
>> > $1:
>> >
>> > $name =~ m/.*\.(\w+)/ or die "'$name' has no extension";
>> >
>> > otherwise you run the risk of picking up $1 from some entirely other
>> > pattern match. The $N variables are slightly strangely scoped, so this
>> > is a little less likely than it might be, but it can and does happen and
>> > causes *very* strange bugs when it does.
>>
>> > As a general rule it's easier to avoid the $N variables where possible,
>> > and instead use the return value of the match:
>>
>> What's so difficult with providing information instead of
>> scaremongering?
>
> I did. I showed the OP how to use $N correctly, and also provided an
> alternative I (at least) find easier to use. Where is the
> scaremongering?
You didn't write anything regarding how the $n actually behave, just
asserted they would be 'strangely scoped' and that this could case
'very strange bugs' in rarely occurring situations. That's about as
sacry as it can get and nothing except scary.
[...]
>> Practically, this means the simple way to use $1 etc correctly is to
>> avoid using them except if the match supposed to set them was
>> successful,
>
> ...as I said...
You didn't. You wrote that it would be necessary to 'check the
success of the match', suggested to use die for tha,t and that -
subject to the nameless but surely grave dangers - this feature
shouldn't be used at all.
>> in this case (assuming that $ext is a hitherto untouched
>> my variable)
>>
>> $name =~ m/.*\.(\w+)/ and $ext = $1;
>
> Ugly and crude. Assigning the return value of the match is much
> cleaner.
Chances are that our aesthetic preferences also differ in other
respects. In this case, however, a nice side effect of this construct
is that nothing is assigned if there wasn't anything to assign. And it
isn't necessary to hack around the fact that the match only returns
the intended value in list context. Actually, I would write this as
$name =~ /.*\.(\w+)/ and $ext = 1;
but I purposely kept the m. If someone's preferred style of writing is
different from mine, I can live with that without seeing a need to
bash him into 'my idea of it'.
>> In more complicated cases,
>>
>> if (<some re match>) {
>> # $1 etc valid here
>> }
>
> That is a useful construction sometimes, but it's usually clearer for
> exceptional flow control ('match failed') to be the branch which diverts
> from the normal flow.
A failed match may well be not 'exceptional' at all. This will usually
be the case for parsing something were multiple kinds of 'input
trings' need to be recognized and analyzed.
[...]
>> <some re match> && do {
>> # also here
>> };
>
> God, that's ugly.
Is this supposed to be some prayer for divine punishment of those
dirty heathens who don't dress like we do, whose accent differs from
our accent, whose haircut differs from ours, whose skin color is
somehow different, who come from different villages and who are
generally foreign scum, easily recognizable by their outlandish and
filthy habits?
------------------------------
Date: Fri, 15 Jun 2012 23:56:54 +0200
From: Martijn Lievaart <m@rtij.nl.invlalid>
Subject: Re: an effective script for grabbing and putting images from or to a website
Message-Id: <6mnsa9-8ia.ln1@news.rtij.nl>
On Wed, 13 Jun 2012 14:45:11 +0100, Ben Morrow wrote:
> This provides the additional advantage of following the proper
> write-close-rename idiom for making a file available atomically
> (probably not important in this case, but it never does any harm).
Maybe not important in this case, but a good habit to get into.
M4
------------------------------
Date: Fri, 15 Jun 2012 17:02:19 -0600
From: Cal Dershowitz <cal@example.invalid>
Subject: Re: an effective script for grabbing and putting images from or to a website
Message-Id: <5c2dnd3ipqJmI0bSnZ2dnUVZ_s6dnZ2d@supernews.com>
On 06/15/2012 03:56 PM, Martijn Lievaart wrote:
> On Wed, 13 Jun 2012 14:45:11 +0100, Ben Morrow wrote:
>
>> This provides the additional advantage of following the proper
>> write-close-rename idiom for making a file available atomically
>> (probably not important in this case, but it never does any harm).
>
> Maybe not important in this case, but a good habit to get into.
There's a second part of the script that I can't quite seem to get
wrangled. I'll excerpt as opposed to making a full listing:
my @files = <$path*>;
my $big_int = 1;
for my $name (@files) {
print "name is $name\n";
$name =~ m/.*\.(w+)/;
my $ext = $1;
print "ext is $ext\n";
}
output:
name is /home/dan/Desktop/upload_luther/lh1.jpg
Use of uninitialized value $ext in concatenation (.) or string at
upload9.pl line 31.
ext is
name is /home/dan/Desktop/upload_luther/lh2.jpg
Use of uninitialized value $ext in concatenation (.) or string at
upload9.pl line 31.
ext is
name is /home/dan/Desktop/upload_luther/lh3.jpg
Use of uninitialized value $ext in concatenation (.) or string at
upload9.pl line 31.
ext is
$
Why does this regex and capture not store 'jpg' in $ext?
--
Cal
------------------------------
Date: Fri, 15 Jun 2012 19:36:38 -0600
From: Cal Dershowitz <cal@example.invalid>
Subject: Re: an effective script for grabbing and putting images from or to a website
Message-Id: <1P2dnaHkkPe6fkbSnZ2dnUVZ_qadnZ2d@supernews.com>
On 06/15/2012 05:02 PM, Cal Dershowitz wrote:
> On 06/15/2012 03:56 PM, Martijn Lievaart wrote:
> There's a second part of the script that I can't quite seem to get
> wrangled. I'll excerpt as opposed to making a full listing:
>
>
> my @files = <$path*>;
>
> my $big_int = 1;
> for my $name (@files) {
> print "name is $name\n";
> $name =~ m/.*\.(w+)/;
> my $ext = $1;
> print "ext is $ext\n";
>
> }
>
> output:
>
> name is /home/dan/Desktop/upload_luther/lh1.jpg
> Use of uninitialized value $ext in concatenation (.) or string at
> upload9.pl line 31.
> ext is
> name is /home/dan/Desktop/upload_luther/lh2.jpg
> Use of uninitialized value $ext in concatenation (.) or string at
> upload9.pl line 31.
> ext is
> name is /home/dan/Desktop/upload_luther/lh3.jpg
> Use of uninitialized value $ext in concatenation (.) or string at
> upload9.pl line 31.
> ext is
> $
>
> Why does this regex and capture not store 'jpg' in $ext?
$ perl upload9.pl
syntax error at upload9.pl line 23, near "/$ext/;"
Execution of upload9.pl aborted due to compilation errors.
$ cat upload9.pl
...
my @list = $ftp->dir();
my $big_int = 1;
for my $name (@files) {
print "name is $name\n";
my ($ext) = $name =~ /([^.]*)$/;
for my $image (@list){
if ( $image =~ m/$ext/;)
print "image is $image\n";
}
print "ext is $ext\n";
}
$
... or how do you match to a variable you already have?
--
Cal
------------------------------
Date: Sat, 16 Jun 2012 16:54:53 +0100
From: Ben Morrow <ben@morrow.me.uk>
Subject: Re: an effective script for grabbing and putting images from or to a website
Message-Id: <drmua9-bee1.ln1@anubis.morrow.me.uk>
Quoth Cal Dershowitz <cal@example.invalid>:
>
> $ perl upload9.pl
> syntax error at upload9.pl line 23, near "/$ext/;"
> Execution of upload9.pl aborted due to compilation errors.
> $ cat upload9.pl
> ...
>
> my @list = $ftp->dir();
> my $big_int = 1;
> for my $name (@files) {
> print "name is $name\n";
You will (or, at least, we will) find your code much easier to read if
you indent it properly.
> my ($ext) = $name =~ /([^.]*)$/;
> for my $image (@list){
> if ( $image =~ m/$ext/;)
There are two syntax errors in that line, neither of which has anything
to do with the pattern match.
> print "image is $image\n";
> }
Ben
------------------------------
Date: Fri, 15 Jun 2012 10:59:07 -0700 (PDT)
From: Nene <rodbass63@gmail.com>
Subject: Learning OOP
Message-Id: <0d4dac96-684f-4608-9c87-b6efb30da872@googlegroups.com>
I want to learn OOP and really understand it.
Below is a snip from the perldoc. A few questions; in the constructor, I see
my $self = {}; Am I creating an annonymous hash called $self?
$self->{NAME} = undef (Is $self the object? and I'm invoking a method called {NAME)? )
Can somebody explain in details the method:
sub name {
my $self = shift;
if (@_) { $self->{NAME} = shift }
return $self->{NAME};
###########################################
package Person;
use strict;
##################################################
## the object constructor (simplistic version) ##
##################################################
sub new {
my $self = {};
$self->{NAME} = undef;
$self->{AGE} = undef;
$self->{PEERS} = [];
bless($self); # but see below
return $self;
}
##############################################
## methods to access per-object data ##
## ##
## With args, they set the value. Without ##
## any, they only retrieve it/them. ##
##############################################
sub name {
my $self = shift;
if (@_) { $self->{NAME} = shift }
return $self->{NAME};
}
sub age {
my $self = shift;
if (@_) { $self->{AGE} = shift }
return $self->{AGE};
}
sub peers {
my $self = shift;
if (@_) { @{ $self->{PEERS} } = @_ }
return @{ $self->{PEERS} };
}
1; # so the require or use succeeds
------------------------------
Date: Fri, 15 Jun 2012 14:08:19 -0700
From: Jim Gibson <jimsgibson@gmail.com>
Subject: Re: Learning OOP
Message-Id: <150620121408198584%jimsgibson@gmail.com>
In article <0d4dac96-684f-4608-9c87-b6efb30da872@googlegroups.com>,
Nene <rodbass63@gmail.com> wrote:
> I want to learn OOP and really understand it.
>
> Below is a snip from the perldoc. A few questions; in the constructor, I see
> my $self = {}; Am I creating an annonymous hash called $self?
You are creating an anonymous hash. Being anonymous, it does not have a
name.
You are then assigning a reference to that anonymous hash to the scalar
variable $self.
>
> $self->{NAME} = undef (Is $self the object? and I'm invoking a method
> called {NAME)? )
You are storing the (key,value) pair ('NAME',undef) in the anonymous
hash referred to by $self. No methods are being called.
$self is probably an object. We would need to see some more code to say
for sure. E.g., is $self ever 'blessed' into a class/package.
>
> Can somebody explain in details the method:
>
> sub name {
> my $self = shift;
> if (@_) { $self->{NAME} = shift }
> return $self->{NAME};
The first value in the array @_, which is used to pass arguments to
subroutines, is shifted off and assigned to $self.
If any values remain in the array @_, the next one ($_[0]) is shifted
off the front of the array and stored in the hash value $self-{NAME}.
The value of $self-{NAME} is returned to the caller.
This is a pattern of method implementation that allows a single method
to be used both as a "getter" and a "setter":
# set name
$self->name("Fred");
# get name
my $name = $self->name();
--
Jim Gibson
------------------------------
Date: Fri, 15 Jun 2012 18:14:47 +0100
From: Rainer Weikusat <rweikusat@mssgmbh.com>
Subject: Re: new topic: I call length($<string>) and get number of lines - code frag below - on MAC OS X 10.7
Message-Id: <87haucqyyg.fsf@sapphire.mobileactivedefense.com>
tmcd@panix.com (Tim McDaniel) writes:
> In article <14kma9-tk.ln1@zem.masonsmusic.co.uk>,
> Justin C <justin.1203@purestblue.com> wrote:
>> local $/; # this sets $/ to undef
>
> I think that a rather more consise way to document that and to assure
> any reader that it is true is
>
> local $/ = undef;
Code is not documentation. The comment informs a reader that $/ is
actually supposed to be undef. The assignment is just useless.
------------------------------
Date: Fri, 15 Jun 2012 17:00:44 +0000 (UTC)
From: tmcd@panix.com (Tim McDaniel)
Subject: Re: new topic: I call length($<string>) and get number of lines - code frag below - on MAC OS X 10.7
Message-Id: <jrfpns$g55$1@reader1.panix.com>
In article <14kma9-tk.ln1@zem.masonsmusic.co.uk>,
Justin C <justin.1203@purestblue.com> wrote:
> local $/; # this sets $/ to undef
I think that a rather more consise way to document that and to assure
any reader that it is true is
local $/ = undef;
or
undef(local $/);
(That latter appears to actually work.)
--
Tim McDaniel, tmcd@panix.com
------------------------------
Date: Fri, 15 Jun 2012 18:19:42 +0100
From: Ben Morrow <ben@morrow.me.uk>
Subject: Re: new topic: I call length($<string>) and get number of lines - code frag below - on MAC OS X 10.7
Message-Id: <ee7sa9-ac6.ln1@anubis.morrow.me.uk>
Quoth tmcd@panix.com:
> In article <14kma9-tk.ln1@zem.masonsmusic.co.uk>,
> Justin C <justin.1203@purestblue.com> wrote:
> > local $/; # this sets $/ to undef
>
> I think that a rather more consise way to document that and to assure
> any reader that it is true is
>
> local $/ = undef;
I would not normally comment anything so simple as that. Adding an
explicit '= undef', rather than a comment, is as confusing as any other
by-definition redundant piece of code: it leaves the reader who already
knows what 'local' does puzzled as to why an explicit assignment should
be needed in this case.
> or
>
> undef(local $/);
>
> (That latter appears to actually work.)
Is that surprising? local returns an lvalue, just like my; this is very
similar in form to the standard
(my $new = $old) =~ s/.../.../;
idiom.
Ben
------------------------------
Date: Fri, 15 Jun 2012 13:12:13 -0700 (PDT)
From: bjlockie <bjlockie@lockie.ca>
Subject: pass array reference
Message-Id: <f2388058-3c11-4b5b-8f2a-24fc7520086d@googlegroups.com>
I'm trying to pass a reference to an array so I can modify it in a function and see the changes outside the function.
I tried:
#!/bin/perl
use strict;
use warnings;
my @myarray = ();
&loadFile( '/etc/resolv.conf', \@myarray );
print "Loaded $#myarray\n";
sub loadFile
{
my $filename = $_[0];
# input as a reference
my (@inputArray) = @{$_[1]};
open( FILE, "<$filename" ) or die "Can't open file ($filename): $!\n";
@inputArray = <FILE>;
close( FILE );
print "Loaded $#inputArray from $filename\n";
}
------------------------------
Date: Fri, 15 Jun 2012 22:02:17 +0100
From: Rainer Weikusat <rweikusat@mssgmbh.com>
Subject: Re: pass array reference
Message-Id: <87bokkwap2.fsf@sapphire.mobileactivedefense.com>
bjlockie <bjlockie@lockie.ca> writes:
> #!/bin/perl
>
> use strict;
> use warnings;
>
> my @myarray = ();
> &loadFile( '/etc/resolv.conf', \@myarray );
Don't use & to invoke a subroutine except if you actually
intend to use its 'special powers': 1. Bypass prototype checking.
2. 'Call forwarding': invoke the subroutine with the current @_ as
'argument vector'.
>
> print "Loaded $#myarray\n";
>
> sub loadFile
> {
> my $filename = $_[0];
> # input as a reference
> my (@inputArray) = @{$_[1]};
Here, you copy the contents of @myarray into @input array. What you
actually need to do is to work with the passed reference, eg
(untested)
my $inputArray = $_[1];
open( FILE, "<$filename" ) or die "Can't open file ($filename): $!\n";
@$inputArray = <FILE>;
close( FILE );
print "Loaded $#$inputArray from $filename\n";
}
------------------------------
Date: Fri, 15 Jun 2012 14:12:53 -0700
From: Jim Gibson <jimsgibson@gmail.com>
Subject: Re: pass array reference
Message-Id: <150620121412535040%jimsgibson@gmail.com>
In article <f2388058-3c11-4b5b-8f2a-24fc7520086d@googlegroups.com>,
bjlockie <bjlockie@lockie.ca> wrote:
> I'm trying to pass a reference to an array so I can modify it in a function
> and see the changes outside the function.
>
> I tried:
>
> #!/bin/perl
>
> use strict;
> use warnings;
>
> my @myarray = ();
> &loadFile( '/etc/resolv.conf', \@myarray );
>
> print "Loaded $#myarray\n";
>
> sub loadFile
> {
> my $filename = $_[0];
> # input as a reference
> my (@inputArray) = @{$_[1]};
>
> open( FILE, "<$filename" ) or die "Can't open file ($filename): $!\n";
> @inputArray = <FILE>;
> close( FILE );
>
> print "Loaded $#inputArray from $filename\n";
> }
You are making a local copy of the array and modifying that. This
should work (untested):
sub loadFile
{
my( $filename, $arrayref ) = @_;
open( my $file, '<', $filename ) or die ...;
@{$arrayref} = <$file>;
close($file);
print( scalar @{$arrayref}, " records read from $filename\n");
}
--
Jim Gibson
------------------------------
Date: Fri, 15 Jun 2012 22:52:31 +0100
From: Rainer Weikusat <rweikusat@mssgmbh.com>
Subject: Re: pass array reference
Message-Id: <874nqcb5uo.fsf@sapphire.mobileactivedefense.com>
Jim Gibson <jimsgibson@gmail.com> writes:
[...]
> sub loadFile
> {
> my( $filename, $arrayref ) = @_;
>
> open( my $file, '<', $filename ) or die ...;
> @{$arrayref} = <$file>;
The curlies are not necessary in this case, cf
Anywhere you'd put an identifier (or chain of identifiers) as
part of a variable or subroutine name, you can replace the
identifier with a simple scalar variable containing a
reference of the correct type:
[perlref(1)]
------------------------------
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:
To submit articles to comp.lang.perl.announce, send your article to
clpa@perl.com.
Back issues are available via anonymous ftp from
ftp://cil-www.oce.orst.edu/pub/perl/old-digests.
#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 V11 Issue 3716
***************************************