[32879] in Perl-Users-Digest

home help back first fref pref prev next nref lref last post

Perl-Users Digest, Issue: 4157 Volume: 11

daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Fri Feb 28 18:09:37 2014

Date: Fri, 28 Feb 2014 15:09:06 -0800 (PST)
From: Perl-Users Digest <Perl-Users-Request@ruby.OCE.ORST.EDU>
To: Perl-Users@ruby.OCE.ORST.EDU (Perl-Users Digest)

Perl-Users Digest           Fri, 28 Feb 2014     Volume: 11 Number: 4157

Today's topics:
    Re: hex print <cwilbur@chromatico.net>
    Re: hex print <ben@morrow.me.uk>
    Re: last iteration of a for loop <ben@morrow.me.uk>
    Re: last iteration of a for loop <gamo@telecable.es>
    Re: last iteration of a for loop <rweikusat@mobileactivedefense.com>
    Re: use strict; use warnings; <m@rtij.nl.invlalid>
    Re: use strict; use warnings; <ben@morrow.me.uk>
    Re: use strict; use warnings; <mach2@hushmail.com>
    Re: use strict; use warnings; <johnblack@nospam.com>
    Re: use strict; use warnings; <rweikusat@mobileactivedefense.com>
    Re: use strict; use warnings; <kaz@kylheku.com>
    Re: use strict; use warnings; <rweikusat@mobileactivedefense.com>
    Re: use strict; use warnings; <johnblack@nospam.com>
    Re: use strict; use warnings; <rweikusat@mobileactivedefense.com>
        using a library <mach2@hushmail.com>
    Re: using a library <triflemenot@protocol.invalid>
    Re: using a library <rweikusat@mobileactivedefense.com>
    Re: using a library <cwilbur@chromatico.net>
    Re: using a library <cwilbur@chromatico.net>
    Re: using a library <mach2@hushmail.com>
    Re: using a library <triflemenot@protocol.invalid>
    Re: using a library <hjp-usenet3@hjp.at>
        Digest Administrivia (Last modified: 6 Apr 01) (Perl-Users-Digest Admin)

----------------------------------------------------------------------

Date: Thu, 27 Feb 2014 14:24:58 -0500
From: Charlton Wilbur <cwilbur@chromatico.net>
Subject: Re: hex print
Message-Id: <878uswnyt1.fsf@new.chromatico.net>

>>>>> "moron" == Trifle Menot <triflemenot@protocol.invalid> writes:

    moron> He still doesn't get it, after you spelled it out for him.

If by "get it" you mean understand the point, you're wrong.  I
understand it just fine; I disagree with it.

If by "get it" you mean agree, that was a lost cause to begin with.  If
ten people say an idiotic thing, it is still an idiotic thing.  If ten
thousand people say an idiotic thing, it is still an idiotic thing, and
they can found a political party.

Charlton



-- 
Charlton Wilbur
cwilbur@chromatico.net


------------------------------

Date: Thu, 27 Feb 2014 23:20:25 +0000
From: Ben Morrow <ben@morrow.me.uk>
Subject: Re: hex print
Message-Id: <pqt4ua-rn31.ln1@anubis.morrow.me.uk>


Quoth "Peter J. Holzer" <hjp-usenet3@hjp.at>:
>
>  The compiler will loop over the source
> text building the byte code[1], the interpreter will loop over the byte
> code.
> 
> [1] Is there a more generic term for this? It's not *byte* code after
> all.

Within the core it's usually called 'the optree'.

Ben



------------------------------

Date: Thu, 27 Feb 2014 23:24:31 +0000
From: Ben Morrow <ben@morrow.me.uk>
Subject: Re: last iteration of a for loop
Message-Id: <f2u4ua-rn31.ln1@anubis.morrow.me.uk>


Quoth Ted Zlatanov <tzz@lifelogs.com>:
> On 26 Feb 2014 14:30:26 GMT hymie@lactose.homelinux.net (hymie!) wrote: 
> 
> h> So I've got a for loop.  It's doing some printing, and at the end of
> h> what it prints, it prints a separator line like
> 
> h> ----------
> 
> h> Is there an easy way that I can tell my loop "don't print the separator
> h> after the last iteration"?
> 
> Easiest way IMO, and a useful idiom regardless:
> 
> #+begin_src perl
> 
> #!/usr/bin/perl
> 
> use warnings;
> use strict;
> 
> my @list = sort keys %ENV;
> 
> while (my $key = pop @list)
> {
>  print "$key\n";
>  print "not last\n" if scalar @list;
>  print "last\n" unless scalar @list;
> }

If you're going to build an array anyway, you might as well just use
join. (If you want more general 'joining', see List::Util::reduce.)

Ben



------------------------------

Date: Fri, 28 Feb 2014 16:05:46 +0100
From: gamo <gamo@telecable.es>
Subject: Re: last iteration of a for loop
Message-Id: <leq8kf$hq9$1@speranza.aioe.org>

El 27/02/14 12:11, Ted Zlatanov escribió:
> my @list = sort keys %ENV;
>
> while (my $key = pop @list)
> {
>   print "$key\n";
>   print "not last\n" if scalar @list;
>   print "last\n" unless scalar @list;
> }


I miss in this discusion a solution using when/default.
Can not be as efficient as using if?

-- 
http://www.telecable.es/personales/gamo/


------------------------------

Date: Fri, 28 Feb 2014 16:06:59 +0000
From: Rainer Weikusat <rweikusat@mobileactivedefense.com>
Subject: Re: last iteration of a for loop
Message-Id: <87ha7jkyqk.fsf@sable.mobileactivedefense.com>

gamo <gamo@telecable.es> writes:
> El 27/02/14 12:11, Ted Zlatanov escribió:
>> my @list = sort keys %ENV;
>>
>> while (my $key = pop @list)
>> {
>>   print "$key\n";
>>   print "not last\n" if scalar @list;
>>   print "last\n" unless scalar @list;
>> }
>
>
> I miss in this discusion a solution using when/default.
> Can not be as efficient as using if?

As contorted because it is just another way of putting
some code into the loop body which simply doesn't belong in there,
hence, execution of it has to be disabled by 'hitting the loop on the
head with a blunt instrument' and as inefficient because some unchanging
fact which was known at the time the code was written needs to be
'reguessed' with a suitable heuristic at run time. It is also as
invasive because it can only work when it is known if the current
element is the last element.

A general workaround is possible based on special-casing the first
element of the "set of things we're iterating over" because it is always
known if the current element is the first element. But this would still
require support at the language level for it to be sanely applicable to
all kinds of supported loops.

Something Wikipedia calls 'loop with test in the middle' can also be
built in Perl:

----------
my $line;

defined($line = <>) and do {
    LOOP: {
	print($line);
	$line = <> // last;
	print("---\n");
	redo;
    }
};
----------

But this works only for loops based on testing a condition, not for
foreach loops.





------------------------------

Date: Thu, 27 Feb 2014 22:31:16 +0100
From: Martijn Lievaart <m@rtij.nl.invlalid>
Subject: Re: use strict; use warnings;
Message-Id: <4en4ua-krc.ln1@news.rtij.nl>

On Thu, 27 Feb 2014 14:46:39 +0000, Rainer Weikusat wrote:

> Martijn Lievaart <m@rtij.nl.invlalid> writes:

>> Look up "leaning toothstick syndrome".
> 
> s/stick/pick

Auch, right.

M4


------------------------------

Date: Thu, 27 Feb 2014 23:16:58 +0000
From: Ben Morrow <ben@morrow.me.uk>
Subject: Re: use strict; use warnings;
Message-Id: <akt4ua-rn31.ln1@anubis.morrow.me.uk>

[Please start a new thread for a new topic.]

Quoth Marek Novotny <mach2@hushmail.com>:
> 
> Just went through a crash course in regex. Ouch that was painful. Dying 
> to get to the full course. This is all too quick for me. 
> 
> Had to modify the card deck...
> 
> #!/usr/bin/perl
> # file: obj12.pl
> #
> # In Lesson 10's Project 1, you wrote a script to shuffle a fake deck 
> # of cards. Copy that script to obj12.pl then make the following 
> additions:
> #
> # Create a loop that prints out the top five cards using regular 
> # expressions to switch the card suit letter with the full name. 
> # (For example, H would become Hearts).
> 
> use strict;
> use warnings;
> 
> my @startingdeck = ("A H","2 H","3 H","4 H","5 H","6 H","7 H","8 H",
>  "9 H","10 H","J H","Q H","K H",
>  "A D","2 D","3 D","4 D","5 D","6 D","7 D","8 D",
>  "9 D","10 D","J D","Q D","K D",
>  "A C","2 C","3 C","4 C","5 C","6 C","7 C","8 C",
>  "9 C","10 C","J C","Q C","K C",
>  "A S","2 S","3 S","4 S","5 S","6 S","7 S","8 S",
>  "9 S","10 S","J S","Q S","K S");
> 
> my $i = 0; my @randomdeck;
> while ($i < 51){
> 	$randomdeck[$i] = shift(@startingdeck); $i++;
> 	$randomdeck[$i] = pop(@startingdeck); $i++;
> }

This loop continues until @startingdeck is empty. There happen to be 52
entries at the moment, but in general it's not a good idea to rely on
'magic numbers' like that:

    while (@startingdeck) {
        push @randomdeck, shift @startingdeck;
        push @randomdeck, pop @startingdeck;
    }

Notice how using 'push' means you can insert at the end of the array
without having to explicitly keep track of how long it is at the moment.

> # obtain top 5 cards and search / replace abbreviations
> 
> $i = 0; my @array;
> while ($i < 5){
> 	$array[$i] = shift(@randomdeck);
> 	$array[$i] =~ s/H/Hearts/;
> 	$array[$i] =~ s/D/Diamonds/;
> 	$array[$i] =~ s/C/Clubs/;
> 	$array[$i] =~ s/S/Spades/;
> 	$i++;
> }

I would write this

    my @print = @randomdeck[0..4];
    for (@print) {
        s/H/Hearts/;
        s/D/Diamonds/;
        s/C/Clubs/;
        s/S/Spades/;
    }

It's worth studying that until you understand how it works. (Some of the
features of Perl here you may not have met yet.) In particular:

    - @array[...] is what's called an 'array slice'. Whereas $array[...]
      returns a single element (using the single index inside the []),
      @array[...] returns a list of elements using the list of indices
      in the [].

    - A for loop loops over the given list of items. If you don't
      specify a variable to use to represent 'the current item', Perl
      defaults to using the special $_ variable.

    - If you use the s/// operator without using =~ to give it a
      variable to operate on, that also defaults to using the $_
      variable.

    - Inside a for loop, the loop variable ($_ in this case) is an
      'alias' to the current element, not a copy. What this means is
      that if you modify $_ inside the loop, it also modifies whichever
      element you're currently working on.

Ben



------------------------------

Date: Thu, 27 Feb 2014 18:41:17 -0600
From: Marek Novotny <mach2@hushmail.com>
Subject: Re: use strict; use warnings;
Message-Id: <R8adnZ3K5N2wRpLOnZ2dnUVZ_rqdnZ2d@supernews.com>

On Thu, 27 Feb 2014 23:16:58 +0000, Ben Morrow wrote:

> It's worth studying that until you understand how it works. (Some of the
> features of Perl here you may not have met yet.) In particular:
> 
>     - @array[...] is what's called an 'array slice'. Whereas $array[...]
>       returns a single element (using the single index inside the []),
>       @array[...] returns a list of elements using the list of indices
>       in the [].
> 
>     - A for loop loops over the given list of items. If you don't
>       specify a variable to use to represent 'the current item', Perl
>       defaults to using the special $_ variable.
> 
>     - If you use the s/// operator without using =~ to give it a
>       variable to operate on, that also defaults to using the $_
>       variable.
> 
>     - Inside a for loop, the loop variable ($_ in this case) is an
>       'alias' to the current element, not a copy. What this means is
>       that if you modify $_ inside the loop, it also modifies whichever
>       element you're currently working on.
> 
> Ben

Thanks Ben,

I have saved all of this and will study it. 



-- 
Marek Novotny
A member of the Linux Foundation
http://www.linuxfoundation.org


------------------------------

Date: Fri, 28 Feb 2014 10:01:23 -0600
From: John Black <johnblack@nospam.com>
Subject: Re: use strict; use warnings;
Message-Id: <MPG.2d7a6ed1faf2768f9897bb@news.eternal-september.org>

In article <87y50xhjyg.fsf@sable.mobileactivedefense.com>, rweikusat@mobileactivedefense.com 
says...
> 
> Ben Morrow <ben@morrow.me.uk> writes:
> > Quoth Rainer Weikusat <rweikusat@mobileactivedefense.com>:
> >> 
> >> > Any sensible modern calendar does include a year or time 0 (usually 1
> >> > BC in year-based systems; other systems like TAI count seconds rather
> >> > than years and have an arbitrarily-chosen 'time 0').
> >> 
> >> That's your misinterpretation of it. As explained above, 'time 0' really
> >> means 'no time passed so far'.
> >
> > No. ISO 8601 years number AD 1 as +1, 1 BC as +0, and 2 BC as -1. If it
> > was counting years before or after some point 1 BC would be -1.
> 
> For systems which measure passing time, 'time 0' means "we start to
> measure now", ie, the POSIX timestamp 1 represents first second which
> passed since the epoch. You're correct about ISO8601 'year numbers' but
> this is a convention which has very likely been designed for 'ease of
> processing' on computers.
> 
> >> Loosely related: There isn't really a 'minute 0' on the clock, that's
> >> minute sixty of the past hour, after which the 'minute counter' wraps
> >> around to zero because the arithmetic is performed in the mod 60
> >> remainder ring.
> >
> > There is no 60 in the mod 60 remainder ring. 60 % 60 = 0.
> 
> ... which is why the minute counter of a digital clock wraps to 0 after the
> 60th minute of an hour has passed ...
> 
> >> I hereby proclaim a much more sensible system of counting that 1st, 2nd, 3rd,
> >> ..., one I call Kelvinism. It goes like this -273,15th, -272.15th,
> >> -271.15th ... Not only does this get rid of this confusing array of
> >> context-depenendent suffixes but it is firmly grounded in laws of
> >> nature!.
> >
> > No, it's grounded in the rather arbitrary choice of the freezing point
> > of water as the basis of the Celsius scale.
> 
> There's no Kelvinism but Kelvinism and the dirty heretics who speak of
> 'Celsian Kelvinism' in order to justify sticking to their
> devil-inspired, pagan superstitions will be arianised in due time!
> 
> (I was actually envisioning the nice possibility of a theological
> schism which is just as pointless, if not more, than the idea itself
> here, as further illustration of the absurdity of the concept).

Wow, this discussion has gotten really far afield.  Here is my opinion (which I am sure 
everyone has been anxiously waiting for...).  When you talk about array locations like:

Arr[50]

people usually call that "location 50" or "Arr 50".  No one would call that location 51, nor 
would they refer to location 0 (Arr[0]) as location 1.  So its preferable not to call 
location 0, the first location or location 50, the 51st location.  Which is why I like the 
idea of calling location 0, the zeroth location.

John Black


------------------------------

Date: Fri, 28 Feb 2014 16:28:41 +0000
From: Rainer Weikusat <rweikusat@mobileactivedefense.com>
Subject: Re: use strict; use warnings;
Message-Id: <87d2i7kxqe.fsf@sable.mobileactivedefense.com>

John Black <johnblack@nospam.com> writes:
> In article <87y50xhjyg.fsf@sable.mobileactivedefense.com>, rweikusat@mobileactivedefense.com: 

[...]

> Arr[50]
>
> people usually call that "location 50" or "Arr 50".  No one would call that location 51, nor 
> would they refer to location 0 (Arr[0]) as location 1.  So its preferable not to call 
> location 0, the first location or location 50, the 51st location.

A 'so' doesn't make a conclusion.


------------------------------

Date: Fri, 28 Feb 2014 19:23:49 +0000 (UTC)
From: Kaz Kylheku <kaz@kylheku.com>
Subject: Re: use strict; use warnings;
Message-Id: <20140228112341.712@kylheku.com>

On 2014-02-28, Rainer Weikusat <rweikusat@mobileactivedefense.com> wrote:
> John Black <johnblack@nospam.com> writes:
>> In article <87y50xhjyg.fsf@sable.mobileactivedefense.com>, rweikusat@mobileactivedefense.com: 
>
> [...]
>
>> Arr[50]
>>
>> people usually call that "location 50" or "Arr 50".  No one would call that location 51, nor 
>> would they refer to location 0 (Arr[0]) as location 1.  So its preferable not to call 
>> location 0, the first location or location 50, the 51st location.
>
> A 'so' doesn't make a conclusion.

I would call that Arr-ea 51. :)


------------------------------

Date: Fri, 28 Feb 2014 19:25:42 +0000
From: Rainer Weikusat <rweikusat@mobileactivedefense.com>
Subject: Re: use strict; use warnings;
Message-Id: <878usvkpjd.fsf@sable.mobileactivedefense.com>

Rainer Weikusat <rweikusat@mobileactivedefense.com> writes:
> John Black <johnblack@nospam.com> writes:
>> In article <87y50xhjyg.fsf@sable.mobileactivedefense.com>, rweikusat@mobileactivedefense.com: 
>
> [...]
>
>> Arr[50]
>>
>> people usually call that "location 50" or "Arr 50".  No one would call that location 51, nor 
>> would they refer to location 0 (Arr[0]) as location 1.  So its preferable not to call 
>> location 0, the first location or location 50, the 51st location.
>
> A 'so' doesn't make a conclusion.

Something more related to Perl: While the tieing mechanism is not really
suited to that because array handling has assumptions about valid
indices baked in, it is nevertheless possible to create 'a Perl array'
which has no location 0:

----
package OffArray;

use Tie::Array;

our @ISA = qw(Tie::Array);

sub TIEARRAY
{
    my ($class, $ofs) = @_;

    return bless({
		  ofs => $ofs,
		  ary => []}, $class);
}

sub FETCH
{
    my ($self, $ndx) = @_;

    $ndx -= $self->{ofs};
    die("index error") if $ndx < 0;
    
    return $self->{ary}[$ndx];
}

sub FETCHSIZE
{
    return scalar(@{$_[0]->{ary}});
}

sub STORE
{
    my ($self, $ndx, $v) = @_;
    
    $ndx -= $self->{ofs};
    die("index error") if $ndx < 0;
    
    return $self->{ary}[$ndx] = $v;
}

sub STORESIZE
{
    my ($self, $count) = @_;
    $#{$self->{ary}} = $count + 1;
}

sub EXISTS
{
    my ($self, $ndx) = @_;

    $ndx -= $self->{ofs};
    return $ndx >= 0 && $ndx < $self->FETCHSIZE();
}

sub PUSH
{
    my ($self, @v) = @_;
    push(@{$self->{ary}}, @v);
}

sub SHIFT
{
    my $self = $_[0];
    return shift(@{$self->{ary}});
}

package main;

my @a;

tie(@a, 'OffArray', 16);

push(@a, $_) for 0 .. 10;
$a[55] = 45;

print("$a[$_]\n") for 16 .. 16 + $#a;

my $count;
while (@a) {
    printf("element %u\t%s\n", ++$count, shift(@a));
}
----

 ... but its contents can still be treated as an ordered sequence of
items and numbers representing this ordering can be assigned to them by
counting items as they appear in the sequence. This is a property the @a
array used above and ordinary Perl arrays have in common. Consequently,
it makes sense to refer to 'the first element' of an array in either
case (and it makes sense to refer to this as 'the first element' because
a count '0 elements' means 'no elements'). Especially considering that
'things which can be regarded as ordered sequence' exist outside of Perl
and they all have 'a first element', even despite the indexing scheme
used for random access may be radically different.




------------------------------

Date: Fri, 28 Feb 2014 15:19:04 -0600
From: John Black <johnblack@nospam.com>
Subject: Re: use strict; use warnings;
Message-Id: <MPG.2d7ab94494272a859897bc@news.eternal-september.org>

In article <87d2i7kxqe.fsf@sable.mobileactivedefense.com>, rweikusat@mobileactivedefense.com 
says...
> 
> John Black <johnblack@nospam.com> writes:
> > In article <87y50xhjyg.fsf@sable.mobileactivedefense.com>, rweikusat@mobileactivedefense.com: 
> 
> [...]
> 
> > Arr[50]
> >
> > people usually call that "location 50" or "Arr 50".  No one would call that location 51, nor 
> > would they refer to location 0 (Arr[0]) as location 1.  So its preferable not to call 
> > location 0, the first location or location 50, the 51st location.
> 
> A 'so' doesn't make a conclusion.

Its location 50, so its also the 50th location.  Why make it confusing?

John Black


------------------------------

Date: Fri, 28 Feb 2014 21:54:24 +0000
From: Rainer Weikusat <rweikusat@mobileactivedefense.com>
Subject: Re: use strict; use warnings;
Message-Id: <87zjla3nu7.fsf@sable.mobileactivedefense.com>

John Black <johnblack@nospam.com> writes:
> In article <87d2i7kxqe.fsf@sable.mobileactivedefense.com>, rweikusat@mobileactivedefense.com 
> says...
>> 
>> John Black <johnblack@nospam.com> writes:
>> > In article <87y50xhjyg.fsf@sable.mobileactivedefense.com>, rweikusat@mobileactivedefense.com: 
>> 
>> [...]
>> 
>> > Arr[50]
>> >
>> > people usually call that "location 50" or "Arr 50".  No one would call that location 51, nor 
>> > would they refer to location 0 (Arr[0]) as location 1.  So its preferable not to call 
>> > location 0, the first location or location 50, the 51st location.
>> 
>> A 'so' doesn't make a conclusion.
>
> Its location 50, so its also the 50th location.  Why make it
> confusing?

I suggest that you ask a few people without 'computing background' how
many 'locations' they expect to be in front of "the 50th location" and
then reconsider your idea of what is and isn't confusing ...


------------------------------

Date: Fri, 28 Feb 2014 12:57:36 -0600
From: Marek Novotny <mach2@hushmail.com>
Subject: using a library
Message-Id: <Ze2dnS2cLfi9QY3OnZ2dnUVZ_qGdnZ2d@supernews.com>

Hi group,

Another weird question. I am going over how to use a Perl script in which 
I send the process to a library to process and then the library returns 
the answer: 

This is one of my Perl scripts:

--begin--------------------------------------

#!/usr/bin/perl
# File: obj13-1.pl
# 
# The script file, obj13-1.pl should get a list of numbers from the user
# (either via STDIN or a list of arguments), call the library function and
# print the returned numbers. Be sure the program gives instructions to
# the user of how to input the numbers and, once the numbers are entered,
# how to complete the program.

use strict;
use warnings;

require 'obj13-lib.pl';

print "\nPlease enter a few numbers then hit <RETURN>: ";
my $input = <STDIN>;

my $average = getaverage($input);
my $total = gettotal($input);
my $div = getdivby2($input);

print "\n";
print "You entered: $input\n"; 
print "The average of your numbers is: $average\n";
print "The total of all your numbers combined is: $total\n";
print "Each of your numbers divided by 2 are: $div\n\n";
print "Have a nice day!!\n\n";

--end---------------------------------

And it makes use of this library:

--begin------------------------------------------

#!/usr/bin/perl
# File: obj13-lib.pl
# 
# The library should contain a function that takes in an array of numbers
# (of arbitrary size). The function will then calculate the average of the
# numbers, the total of all of the numbers added together, and a new array
# of numbers which is comprised of the original input numbers each divided
# by 2. It will then return a new list with all of that information.

use strict;
use warnings;

sub getdivby2{
	my $input = shift(@_);
	chomp($input);
	my @numbers = split(/ /,$input);
	my @divided = @numbers;
	my $elem;	
	foreach $elem(@divided){
		$elem/=2;
		}
	my $divided = join(" ",@divided);
	return $divided;
}

sub getaverage{
	my $input = shift(@_);
	chomp($input);
	my @numbers = split(/ /,$input);
	my $qty = $#numbers +1;
	my $combined;	
	$combined += $_ for @numbers;
	my $average = ($combined / $qty);
	return $average;
}

sub gettotal{
	my $input = shift(@_);
	chomp($input);
	my @numbers = split(/ /,$input);
	my $combined;	
	$combined += $_ for @numbers;
	return $combined;
}

1;	
-----------end-------------------------

My question is this. In the above example I take an array and convert it 
to a string where it is passed to the library where the string is 
converted back to an array. Then I process my answer, which is converted 
to a string and returned back to the Perl script. 

Can I simply pass an array without conversion to a string??

I am doing it this way as I am basing it off an example I have which 
works similar to this. 

Thanks, 

-- 
Marek Novotny
A member of the Linux Foundation
http://www.linuxfoundation.org


------------------------------

Date: Fri, 28 Feb 2014 19:36:49 +0000
From: Trifle Menot <triflemenot@protocol.invalid>
Subject: Re: using a library
Message-Id: <d3p1h9pg6dddqfudu7eh56br9su49lv4cc@4ax.com>

On Fri, 28 Feb 2014 12:57:36 -0600, Marek Novotny <mach2@hushmail.com>
wrote:

> Can I simply pass an array without conversion to a string??

perlreftut says:

> A reference is a scalar value that refers to an entire array
> or an entire hash (or to just about anything else).

So you could pass a reference to the array. Like passing a pointer in C.
The syntax for using it can be tricky though.




------------------------------

Date: Fri, 28 Feb 2014 20:07:06 +0000
From: Rainer Weikusat <rweikusat@mobileactivedefense.com>
Subject: Re: using a library
Message-Id: <874n3jknmd.fsf@sable.mobileactivedefense.com>

Marek Novotny <mach2@hushmail.com> writes:
> Another weird question. I am going over how to use a Perl script in which 
> I send the process to a library to process and then the library returns 
> the answer: 

[...]

> My question is this. In the above example I take an array and convert it 
> to a string where it is passed to the library where the string is 
> converted back to an array. Then I process my answer, which is converted 
> to a string and returned back to the Perl script. 
>
> Can I simply pass an array without conversion to a string??

For the examples you gave, you could pass a list of arguments and return
a list of values eg

-----
sub print_list
{
    print(join("\n", @_), "\n");
}

sub getdivby2
{
    return map { $_ / 2 } @_;
}

my @a = (1,2,3,4,5);

print_list(getdivby2(@a));
------




	


------------------------------

Date: Fri, 28 Feb 2014 15:24:51 -0500
From: Charlton Wilbur <cwilbur@chromatico.net>
Subject: Re: using a library
Message-Id: <87sir3m1d8.fsf@new.chromatico.net>

>>>>> "MN" == Marek Novotny <mach2@hushmail.com> writes:

    MN> My question is this. In the above example I take an array and
    MN> convert it to a string where it is passed to the library where
    MN> the string is converted back to an array. Then I process my
    MN> answer, which is converted to a string and returned back to the
    MN> Perl script.

    MN> Can I simply pass an array without conversion to a string??

The library expects a string of space-separated numbers, so unless you
modify the library, you must pass in a string.

And you can pass in an array, but you'll be safer passing it in as an
array reference -- see perldoc perlreftut.

Charlton



-- 
Charlton Wilbur
cwilbur@chromatico.net


------------------------------

Date: Fri, 28 Feb 2014 15:26:50 -0500
From: Charlton Wilbur <cwilbur@chromatico.net>
Subject: Re: using a library
Message-Id: <87ob1rm19x.fsf@new.chromatico.net>

>>>>> "TM" == Trifle Menot <triflemenot@protocol.invalid> writes:

    TM> So you could pass a reference to the array. Like passing a
    TM> pointer in C.  The syntax for using it can be tricky though.

Tricky?  It would appear that the value of the advice is directly
proportional to the author's willingness to sign his name to it.

sub foo {
    my ($name, $aref) = @_;
    my @arr = @$aref;

}

foo ('name', [1, 2, 3]);

Charlton



-- 
Charlton Wilbur
cwilbur@chromatico.net


------------------------------

Date: Fri, 28 Feb 2014 15:18:23 -0600
From: Marek Novotny <mach2@hushmail.com>
Subject: Re: using a library
Message-Id: <Ze2dnSycLfiCYI3OnZ2dnUVZ_qGdnZ2d@supernews.com>

On Fri, 28 Feb 2014 15:26:50 -0500, Charlton Wilbur wrote:

>>>>>> "TM" == Trifle Menot <triflemenot@protocol.invalid> writes:
> 
>     TM> So you could pass a reference to the array. Like passing a TM>
>     pointer in C.  The syntax for using it can be tricky though.
> 
> Tricky?  It would appear that the value of the advice is directly
> proportional to the author's willingness to sign his name to it.
> 
> sub foo {
>     my ($name, $aref) = @_;
>     my @arr = @$aref;
> 
> }
> 
> foo ('name', [1, 2, 3]);
> 
> Charlton

Thanks everyone. I think I may have stumbled onto a solution that seems 
to fit in my test so far. I'll post the whole thing as soon as I am 
finished writing it. So far, it looks much easier than I thought. 

Best, 

-- 
Marek Novotny
A member of the Linux Foundation
http://www.linuxfoundation.org


------------------------------

Date: Fri, 28 Feb 2014 21:39:42 +0000
From: Trifle Menot <triflemenot@protocol.invalid>
Subject: Re: using a library
Message-Id: <aqv1h91uifmerbs9cso3ativkb1mcq0q1j@4ax.com>

On Fri, 28 Feb 2014 15:26:50 -0500, Charlton Wilbur
<cwilbur@chromatico.net> wrote:

>    TM> So you could pass a reference to the array. Like passing a
>    TM> pointer in C.  The syntax for using it can be tricky though.
>
>Tricky?  It would appear that the value of the advice is directly
>proportional to the author's willingness to sign his name to it.

I see my posts get you all riled up. Another usenet stalker.

<plonk>



------------------------------

Date: Fri, 28 Feb 2014 22:48:54 +0100
From: "Peter J. Holzer" <hjp-usenet3@hjp.at>
Subject: Re: using a library
Message-Id: <slrnlh2126.ar3.hjp-usenet3@hrunkner.hjp.at>

On 2014-02-28 18:57, Marek Novotny <mach2@hushmail.com> wrote:
> Another weird question. I am going over how to use a Perl script in which 
> I send the process to a library to process and then the library returns 
> the answer: 
>
> This is one of my Perl scripts:
>
> --begin--------------------------------------
[...]
> my $input = <STDIN>;
>
> my $average = getaverage($input);
> my $total = gettotal($input);
> my $div = getdivby2($input);
[...]
> --end---------------------------------
>
> And it makes use of this library:
>
> --begin------------------------------------------
[...]
> sub getdivby2{
> 	my $input = shift(@_);
> 	chomp($input);
> 	my @numbers = split(/ /,$input);
> 	my @divided = @numbers;
> 	my $elem;	
> 	foreach $elem(@divided){
> 		$elem/=2;
> 		}
> 	my $divided = join(" ",@divided);
> 	return $divided;
> }
[...]
> -----------end-------------------------
>
> My question is this. In the above example I take an array and convert it 
> to a string where it is passed to the library

You do? Where? I see only $input being passed "to the library" (I would
say it is passed to the functions in the library), and that is read from
stdin, not converted from an array.

> where the string is 
> converted back to an array. Then I process my answer, which is converted 
> to a string and returned back to the Perl script. 
>
> Can I simply pass an array without conversion to a string??

Yes. Indeed you can see a hint in the first line of your functions:

> 	my $input = shift(@_);

This takes the first element of @_ and shoves it into $input. What is
@_? It's an array holding the parameters with which the function was
called. So instead of using just the first one, we use them all:

sub getdivby2 {
    my @numbers = @_;
    for (@numbers) {
        $_ /= 2;
    }
    return @numbers;
}

And as you can see here, I just return an array as well. Perl functions
can return lists, not just scalar values. (there is also a difference
between lists and arrays, which we like to discuss at great length, but
for now you can just assume that these are synonyms).

And then you can call the function the way you would expect:

my @numbers =split($input);
my @div = getdivby2(@numbers);
say "@div";

@div = getdivby2(2, 3, 4);
say "@div";

@numbers = (2, 3);

@div = getdivby2(1, @numbers, 4);
say "@div";

(the last example is probably why Charlton wrote that passing a
reference to an array is safer).

        hp

-- 
   _  | Peter J. Holzer    | Fluch der elektronischen Textverarbeitung:
|_|_) |                    | Man feilt solange an seinen Text um, bis
| |   | hjp@hjp.at         | die Satzbestandteile des Satzes nicht mehr
__/   | http://www.hjp.at/ | zusammenpaßt. -- Ralph Babel


------------------------------

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 4157
***************************************


home help back first fref pref prev next nref lref last post