[32093] in Perl-Users-Digest

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

Perl-Users Digest, Issue: 3357 Volume: 11

daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Tue Apr 19 16:09:28 2011

Date: Tue, 19 Apr 2011 13:09:12 -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           Tue, 19 Apr 2011     Volume: 11 Number: 3357

Today's topics:
        A regex to search for numeric ranges... <misterperl@gmail.com>
    Re: A regex to search for numeric ranges... <*@eli.users.panix.com>
        fork and blocking... <zihav@yahoo.com>
    Re: fork and blocking... <tzz@lifelogs.com>
    Re: fork and blocking... <jimsgibson@gmail.com>
    Re: grabbing a facebook group <sherm.pendley@gmail.com>
    Re: Learning by example <cartercc@gmail.com>
        parsing a command line, but not the usual problem <*@eli.users.panix.com>
    Re: parsing a command line, but not the usual problem (Randal L. Schwartz)
        Perl RegExp question <keithdlee2000@gmail.com>
    Re: Perl RegExp question <tadmc@seesig.invalid>
    Re: Perl RegExp question <cartercc@gmail.com>
    Re: Perl RegExp question <keithdlee2000@gmail.com>
    Re: Perl RegExp question <cartercc@gmail.com>
    Re: Perl RegExp question <keithdlee2000@gmail.com>
    Re: Perl RegExp question <tzz@lifelogs.com>
        Spreadsheet::WriteExcel, can't write to returned object <justin.1104@purestblue.com>
    Re: Spreadsheet::WriteExcel, can't write to returned ob <jimsgibson@gmail.com>
    Re: to eval or not to eval? <tadmc@seesig.invalid>
    Re: to eval or not to eval? <marc.girod@gmail.com>
    Re: to eval or not to eval? <marc.girod@gmail.com>
        Digest Administrivia (Last modified: 6 Apr 01) (Perl-Users-Digest Admin)

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

Date: Tue, 19 Apr 2011 12:35:56 -0700 (PDT)
From: Mr P <misterperl@gmail.com>
Subject: A regex to search for numeric ranges...
Message-Id: <5e2d8dc3-4e2b-4723-b916-f39596a71323@l36g2000vbp.googlegroups.com>

I read up on this on the www and I found ideas like

if ( /\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b/ ) ...

which is pretty uncipherable at a glance and just in general not
elegant in any sense.

I generally do something like

 if ( /(\d+)/ && $1 > 256 && $1 < 1024 )


Which to me is a lot more readable at a glance, but like the example
above not overly elegant..

But what I'd REALLY like to do is, similar to the  trick for numeric
sort, a way to do it in the regex like

/[256-1024]/ # but force it to be numeric, not literal perhaps with a
switch

Thoughts, Masters?


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

Date: Tue, 19 Apr 2011 19:57:52 +0000 (UTC)
From: Eli the Bearded <*@eli.users.panix.com>
Subject: Re: A regex to search for numeric ranges...
Message-Id: <eli$1104191546@qz.little-neck.ny.us>

In comp.lang.perl.misc, Mr P  <misterperl@gmail.com> wrote:
> I read up on this on the www and I found ideas like
> 
> if ( /\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b/ ) ...
> 
> which is pretty uncipherable at a glance and just in general not
> elegant in any sense.

True. That's why it's much better to not use regexps for numerical
ranges.

> I generally do something like
> 
>  if ( /(\d+)/ && $1 > 256 && $1 < 1024 )

I'd write that as

   if ( /(\d+)/ && ($1 > 256) && ($1 < 1024) )

because I like to make sure things operate in the order I want them
to.

> Which to me is a lot more readable at a glance, but like the example
> above not overly elegant..
> 
> But what I'd REALLY like to do is, similar to the  trick for numeric
> sort, a way to do it in the regex like
> 
> /[256-1024]/ # but force it to be numeric, not literal perhaps with a
> switch

sub mknumre($$) {
  my $low = shift;
  my $hi  = shift;

  my $set = join('|', ($low .. $hi));

  return qr/($set)/;
}

That doesn't optimize for size of expression. Nor does it consider
word boundaries ("456654" would match), if leading zeros should be
disallowed, if "256.2" can be accepted, etc, etc, etc.

> Thoughts, Masters?

Why does this have to be a regular expression? Use the right tool
for the job.

Elijah
------
loves the qr// operator


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

Date: Tue, 19 Apr 2011 08:42:39 -0700 (PDT)
From: Tom <zihav@yahoo.com>
Subject: fork and blocking...
Message-Id: <c8e7cb0d-9b42-4467-b1e5-5c30f950f880@e26g2000vbz.googlegroups.com>

Greetings,

    I need a little help with forking, I got the following code off
the web and modified for doing "df" on file systems. I hope to change
this to "rsync" at some point. The problem is I don't want to run any
more that 5 rsyncs at a time. The forking is working fine, however my
blocking isn't... It gets the first 5 off fine but never decrements
the counter I'm using for blocking. Is there a better way than using a
counter?

Thanks in Advanced!
     Tom



my @childs;
my @FILESYSTEMS=("Alienbrain_Proxy", "programs", "cae", "codesign",
"eng", "Gold_Build_Patches", "Gold_Builds", "Gold_Patches", "hwdev",
"Media_Shares");

$blockcount = 0;
foreach $item ( @FILESYSTEMS ) {
       $blockcount++;
       print "$item\n";
        while ( $blockcount > 4 ) {
            print "$blockcount\n";
            sleep 1;
        }
            my $pid = fork();
        if ($pid) {
        # parent
#            print "pid is $pid, parent $$\n";
            push(@childs, $pid);
        } elsif ($pid == 0) {
                # child
             fsize ("$item");
            $blockcount--;
            exit 0;
        } else {
                die "Couldn't Fork!: $!\n";
        }
}

foreach (@childs) {
        my $tmp = waitpid($_, 0);
         print "Done with pid $tmp\n";
}

print "End of main program\n";


sub fsize {
        my $input = shift;
        system ("df /net/server1/$input/$input > /tmp/$input.log");
}


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

Date: Tue, 19 Apr 2011 13:00:36 -0500
From: Ted Zlatanov <tzz@lifelogs.com>
Subject: Re: fork and blocking...
Message-Id: <87zknmf7ej.fsf@lifelogs.com>

On Tue, 19 Apr 2011 08:42:39 -0700 (PDT) Tom <zihav@yahoo.com> wrote: 

T>     I need a little help with forking, I got the following code off
T> the web and modified for doing "df" on file systems. I hope to change
T> this to "rsync" at some point. The problem is I don't want to run any
T> more that 5 rsyncs at a time. The forking is working fine, however my
T> blocking isn't... It gets the first 5 off fine but never decrements
T> the counter I'm using for blocking. Is there a better way than using a
T> counter?

Have you looked at Parallel::ForkManager 
(http://search.cpan.org/~dlux/Parallel-ForkManager-0.7.5/ForkManager.pm)?

Ted


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

Date: Tue, 19 Apr 2011 11:16:22 -0700
From: Jim Gibson <jimsgibson@gmail.com>
Subject: Re: fork and blocking...
Message-Id: <190420111116226530%jimsgibson@gmail.com>

In article
<c8e7cb0d-9b42-4467-b1e5-5c30f950f880@e26g2000vbz.googlegroups.com>,
Tom <zihav@yahoo.com> wrote:

> Greetings,
> 
>     I need a little help with forking, I got the following code off
> the web and modified for doing "df" on file systems. I hope to change
> this to "rsync" at some point. The problem is I don't want to run any
> more that 5 rsyncs at a time. The forking is working fine, however my
> blocking isn't... It gets the first 5 off fine but never decrements
> the counter I'm using for blocking. Is there a better way than using a
> counter?
> 
> Thanks in Advanced!
>      Tom
> 
> 
> 
> my @childs;
> my @FILESYSTEMS=("Alienbrain_Proxy", "programs", "cae", "codesign",
> "eng", "Gold_Build_Patches", "Gold_Builds", "Gold_Patches", "hwdev",
> "Media_Shares");
> 
> $blockcount = 0;
> foreach $item ( @FILESYSTEMS ) {
>        $blockcount++;
>        print "$item\n";
>         while ( $blockcount > 4 ) {
>             print "$blockcount\n";
>             sleep 1;
>         }

Once you get into this loop, when $blockcount > 4, you never get out.
You are in an infinite loop. Decrementing $blockcount is done by lines
below, but they never get executed. You will need to add a wait
statement here, waiting until one of your child processes has
completed, then decrementing $blockcount and removing the child process
from the array of PIDs. 

>             my $pid = fork();
>         if ($pid) {
>         # parent
> #            print "pid is $pid, parent $$\n";
>             push(@childs, $pid);
>         } elsif ($pid == 0) {
>                 # child
>              fsize ("$item");
>             $blockcount--;
>             exit 0;
>         } else {
>                 die "Couldn't Fork!: $!\n";
>         }
> }
> 
> foreach (@childs) {
>         my $tmp = waitpid($_, 0);
>          print "Done with pid $tmp\n";
> }
> 
> print "End of main program\n";
> 
> 
> sub fsize {
>         my $input = shift;
>         system ("df /net/server1/$input/$input > /tmp/$input.log");
> }

-- 
Jim Gibson


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

Date: Tue, 19 Apr 2011 15:43:18 -0400
From: Sherm Pendley <sherm.pendley@gmail.com>
Subject: Re: grabbing a facebook group
Message-Id: <m2ipuani21.fsf@sherm.shermpendley.com>

Uno <Uno@example.invalid> writes:

> $ cat fb1.pl
>  #!/usr/bin/perl
> use strict;
>
> Are you stoned?  Tad, if either being correct or promoting the
> discussion in c.l.p.misc is part of your job description, I think you
> need to resign.

"Uno," get a grip. The space before the #! caused the OS to run the file
as a *shell script*. Once that happened, Perl wasn't involved at all.

I'd like to help you, but you're about one ill-informed rant away from
being permanently ignored here.

sherm--

-- 
Sherm Pendley
                                   <http://camelbones.sourceforge.net>
Cocoa Developer


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

Date: Tue, 19 Apr 2011 06:21:37 -0700 (PDT)
From: ccc31807 <cartercc@gmail.com>
Subject: Re: Learning by example
Message-Id: <dc75e75d-031d-4a03-a155-ed3310bfdcf9@q12g2000prb.googlegroups.com>

On Apr 19, 5:04=A0am, Justin C <justin.1...@purestblue.com> wrote:
> > Bottom line: use Perl daily, writing real solutions to real tasks.
>
> I don't have enough tasks for which I can use Perl.

I have exactly the same problem with two languages that I've been
attempting to learn for years: Prolog and Common Lisp. What I said
about having a reason to use the technology I've learned by hard
personal experience.

> I do, though, have a
> lot of Perl I've written over the last however many years, and I know I
> can improve on some of the early stuff.

Bingo! Every time I run a process that I've developed, I review the
code and REWRITE it. I have a lot of stuff that I do four or five
times a year, and this is long enough to forget what you've written
(and why in some cases) but short enough so that you can understand
the requirements. It also helps if you upgrade your Perl with the new
versions.

Unfortunately, 'management' seems to have the attitude that, if it
ain't broke, you shouldn't fix it. I have a corpus of scripts that
I've written for managers over the years that break from time to time,
and I cringe every time I look at one. ;-)

CC.


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

Date: Tue, 19 Apr 2011 18:28:02 +0000 (UTC)
From: Eli the Bearded <*@eli.users.panix.com>
Subject: parsing a command line, but not the usual problem
Message-Id: <eli$1104191414@qz.little-neck.ny.us>

I'm well versed in how to parse the arguments passed into my
script. The program is in $0 and all of the individual arguments
are in @ARGV. Running through that array and doing things is easy.

What I'm interested in doing is parsing a string into those values,
a task normally done by the shell.

#!/usr/bin/perl -w
# Naive command line parsing.

use strict;

print "Try a command:\n";
my $line      = <STDIN>;

my @argvector = split(/\s+/, $line);
my $progname  = shift(@argvector);

print "Prog {$progname} args: " . join(', ', @argvector) . "\n";
__END__

$ perl /tmp/naive
Try a command:
echo this is a 'command line' but it has "some $faults"
Prog {echo} args: this, is, a, 'command, line', but, it, has, "some, $faults"
$

Are there any modules that can help me with this breed of command
parsing? Regular command line parsing is dominating my search results.
I would like to be able to do variable expansion in double-quoted
strings and no expansion in single-quoted ones. I am not interested
in file globbing.

Elijah
------
figures someone has had this problem before


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

Date: Tue, 19 Apr 2011 12:52:09 -0700
From: merlyn@stonehenge.com (Randal L. Schwartz)
To: Eli the Bearded <*@eli.users.panix.com>
Subject: Re: parsing a command line, but not the usual problem
Message-Id: <86zknm3tp2.fsf@red.stonehenge.com>

>>>>> "EtB" == Eli the Bearded <*@eli.users.panix.com> writes:

EtB> Are there any modules that can help me with this breed of command
EtB> parsing? Regular command line parsing is dominating my search results.
EtB> I would like to be able to do variable expansion in double-quoted
EtB> strings and no expansion in single-quoted ones. I am not interested
EtB> in file globbing.

Looks like Shell::Parser could do it, although it might be overkill.

-- 
Randal L. Schwartz - Stonehenge Consulting Services, Inc. - +1 503 777 0095
<merlyn@stonehenge.com> <URL:http://www.stonehenge.com/merlyn/>
Smalltalk/Perl/Unix consulting, Technical writing, Comedy, etc. etc.
See http://methodsandmessages.posterous.com/ for Smalltalk discussion


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

Date: Tue, 19 Apr 2011 12:04:22 +0000 (UTC)
From: Keith <keithdlee2000@gmail.com>
Subject: Perl RegExp question
Message-Id: <iojto6$53e$1@dont-email.me>

All:
 I am having a problem with Perl's regular expressions.  

I am trying to change this --
King of the Forest Rangers S.O.S. Ranger  Chapter 9.AVI

To this --
King of the Forest Rangers Ch 9 S.O.S. Ranger.avi

I tried to use this regexp but it didn't work as expected --
s/^(.*)(\s*)(.*)(\s*)(Chapter)(\s*)(\d*).AVI/$1 Ch $7 $3.avi/g

All I got was this --
King of the Forest Rangers S.O.S. Ranger  Ch 9.avi

How do I make a Perl regexp that works with any number of strings at the beginning (the title of the file), 
any number of strings in the middle (the title of that file's episode) and the Chapter number?  




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

Date: Tue, 19 Apr 2011 08:02:08 -0500
From: Tad McClellan <tadmc@seesig.invalid>
Subject: Re: Perl RegExp question
Message-Id: <slrniqr1ll.o05.tadmc@tadbox.sbcglobal.net>

Keith <keithdlee2000@gmail.com> wrote:

>  I am having a problem with Perl's regular expressions.  


Actually, you are having a problem with how your input is formatted.


> I am trying to change this --
> King of the Forest Rangers S.O.S. Ranger  Chapter 9.AVI
>
> To this --
> King of the Forest Rangers Ch 9 S.O.S. Ranger.avi
>
> I tried to use this regexp but it didn't work as expected --
> s/^(.*)(\s*)(.*)(\s*)(Chapter)(\s*)(\d*).AVI/$1 Ch $7 $3.avi/g
>
> All I got was this --
> King of the Forest Rangers S.O.S. Ranger  Ch 9.avi
>
> How do I make a Perl regexp that works with any number of strings at the beginning (the title of the file), 
> any number of strings in the middle (the title of that file's episode) and the Chapter number?  

For the string

    King of the Forest Rangers S.O.S. Ranger

there are 8 different ways of matching "any number of words 
followed by any number of words":

    ()
    (King of the Forest Rangers S.O.S. Ranger)
    
    (King) 
    (of the Forest Rangers S.O.S. Ranger)

    (King of) 
    (the Forest Rangers S.O.S. Ranger)

    (King of the) 
    (Forest Rangers S.O.S. Ranger)

    (King of the Forest) 
    (Rangers S.O.S. Ranger)

    (King of the Forest Rangers) 
    (S.O.S. Ranger)

    (King of the Forest Rangers S.O.S.) 
    (Ranger)

    (King of the Forest Rangers S.O.S. Ranger)
    ()


So, which one is the one you want?

How can you tell where the title ends and the episode begins?

If you cannot do that, then you cannot solve this problem.

Wherever you have gotten the data from made it into hamburger, 
you cannot turn it back into steak. (i.e. fix your data)



-- 
Tad McClellan
email: perl -le "print scalar reverse qq/moc.liamg\100cm.j.dat/"
The above message is a Usenet post.
I don't recall having given anyone permission to use it on a Web site.


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

Date: Tue, 19 Apr 2011 06:12:24 -0700 (PDT)
From: ccc31807 <cartercc@gmail.com>
Subject: Re: Perl RegExp question
Message-Id: <710602f4-0f00-45f3-813a-c9882f95cc25@x8g2000prh.googlegroups.com>

On Apr 19, 8:04=A0am, Keith <keithdlee2...@gmail.com> wrote:
> I am trying to change this --
> King of the Forest Rangers S.O.S. Ranger =A0Chapter 9.AVI
>
> To this --
> King of the Forest Rangers Ch 9 S.O.S. Ranger.avi

The Perl mavens will tar and feather me for saying this, but I'll say
it anyway. And BTW, this is true not only for Perl but also for
anything that uses REs (like vi, for example).

Build up your RE piece by piece. This is somewhat difficult to do
without a top loop (like Lisp) but you can still do it. Match your
original term by term, using the $1, $2, etc., variables to see what
you get. Also, the prematch and postmatch variables ($', $`, and kin)
variables are eyeopening as well. Look at perlvar.

My strategy, which isn't the best by any means, is to start from the
front and match token by token, until I can capture everything I want
in the numbered variables, and then the job is as good as done. I find
it much harder to compose a RE in one stroke -- it's better to have
one that does ten percent of what it's supposed to do than to have one
that does 100 percent of nothing.

CC.


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

Date: Tue, 19 Apr 2011 15:21:51 +0000 (UTC)
From: Keith <keithdlee2000@gmail.com>
Subject: Re: Perl RegExp question
Message-Id: <iok9af$i36$1@dont-email.me>

CC:
  But how does one match a title that in one example starts off with "King of the Royal Mounties" and 
another that has as it's title "King's Row"?  Is there a global RE that takes care of such titles or are each 
controlled by the number of words in each file's title?


Keith


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

Date: Tue, 19 Apr 2011 08:48:28 -0700 (PDT)
From: ccc31807 <cartercc@gmail.com>
Subject: Re: Perl RegExp question
Message-Id: <103257a2-9073-4602-8a89-cceed51370d8@x37g2000prb.googlegroups.com>

On Apr 19, 11:21=A0am, Keith <keithdlee2...@gmail.com> wrote:
> =A0 But how does one match a title that in one example starts off with "K=
ing of the Royal Mounties" and
> another that has as it's title "King's Row"? =A0Is there a global RE that=
 takes care of such titles or are each
> controlled by the number of words in each file's title?

That's not what you have. You have a sequence of tokens separated by
white space, most composed of alphabetical characters, some of numeric
characters, some both, and some with non-alphanumeric characters. It's
possible to have a non-alphanumeric character in a title, like 'King's
Row'.

You can't match what you don't have, and you don't have a book title.
If you want to consider everything before the literal string 'Chapter'
as the title, you can do that, but that's a characteristic you impose
on the data, not something that's inherent in the data.

Of course, in a case like this one, where you are reading in a mass of
character data, you should normalize the data in some way -- something
that Perl excels at. You should also assume that you will get error
lines, and write those out to an error file.

It might be helpful if you could post several dozen lines of your
input data.

CC.


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

Date: Tue, 19 Apr 2011 16:46:37 +0000 (UTC)
From: Keith <keithdlee2000@gmail.com>
Subject: Re: Perl RegExp question
Message-Id: <ioke9d$euh$1@dont-email.me>

CC:
 OK, I understand now.  Here are some more examples of input and wanted output.

 Title of show -- "King of Royal Mounted" or "King's Row"
 Titlle of episode --  "Murderer's Row" or "Saps at Sea"
 Number of episode -- 1 through 13

Input Examples:
  King of Royal Mounted Murderer's Row Chapter 2.AVI

  King's Row Saps at Sea  Chapter 11.AVI


  Again, how do I make some generic regexp in Perl in order to change the above to the following output?

Output Examples:
    King of Royal Mounted Ch 2 Murderer's Row.avi

    King's Row Ch 11 Saps at Sea.avi


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

Date: Tue, 19 Apr 2011 13:03:58 -0500
From: Ted Zlatanov <tzz@lifelogs.com>
Subject: Re: Perl RegExp question
Message-Id: <87vcyaf78x.fsf@lifelogs.com>

On Tue, 19 Apr 2011 16:46:37 +0000 (UTC) Keith <keithdlee2000@gmail.com> wrote: 

K>  OK, I understand now.  Here are some more examples of input and wanted output.

K>  Title of show -- "King of Royal Mounted" or "King's Row"
K>  Titlle of episode --  "Murderer's Row" or "Saps at Sea"
K>  Number of episode -- 1 through 13

K> Input Examples:
K>   King of Royal Mounted Murderer's Row Chapter 2.AVI

K>   King's Row Saps at Sea  Chapter 11.AVI


K>   Again, how do I make some generic regexp in Perl in order to change the above to the following output?

K> Output Examples:
K>     King of Royal Mounted Ch 2 Murderer's Row.avi

K>     King's Row Ch 11 Saps at Sea.avi

Build a list of possible show names.  Untested:

my @shows = ('King of Royal Mounted', "King's Row");
foreach my $show (@shows)
{
 # note the i modifier to match AVI, avi, etc.
 $name =~ s/^$show\s+(.*)\s+Chapter\s+(\d+).avi/$show Ch $2 $1.avi/i;
}

Ted


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

Date: Tue, 19 Apr 2011 16:33:00 +0100
From: Justin C <justin.1104@purestblue.com>
Subject: Spreadsheet::WriteExcel, can't write to returned object?
Message-Id: <cim088-vlu.ln1@zem.masonsmusic.co.uk>


$deity knows if I've got the terminology right on this. I'm trying to
tidy up an old program that extracts some stuff from one Excel
spreadsheet, munges it a little, and then puts it into another
spreadsheet. My method of tidying is, in this instance, to take all of
the bits and put them into subroutines so that the main program looks a
lot cleaner.

So I *had*:
#!/usr/bin/perl

use strict;
use warnings;
use Spreadsheet::WriteExcel;

my $file = 'delete_me.xls';
my $workbook = Spreadsheet::WriteExcel->new($file);
my $excel = $workbook->add_worksheet();

for my $row ( 0 .. 99 ) {
	for my $col ( 0 .. 9 ) {
		my $str = $row * $col;
		$excel->write_string($row, $col, $str);
	}
}

That works as expected. I wanted to 'tidy away' the creation of the file and worksheet (I've also got some formatting coding there too in my real program). So here's what I made:

#!/usr/bin/perl

use strict;
use warnings;
use Spreadsheet::WriteExcel;

my $file = 'delete_me.xls';
my $excel = create_excel_file($file);

for my $row ( 0 .. 99 ) {
	for my $col ( 0 .. 9 ) {
		my $str = $row * $col;
		$excel->write_string($row, $col, $str);
	}
}

sub create_excel_file {
	my $of = shift;
	my $workbook = Spreadsheet::WriteExcel->new($of);
	my $worksheet = $workbook->add_worksheet();
	return $worksheet;
}

This creates an empty file, the returned worksheet object doesn't get
anything printed to it, nor do I get any errors or warnings. I tried
returning \$worksheet but then the $exel->write_string line complained
"Can't call method ... on an unblessed reference".

This is probably where we see gaping holes in my Perl understanding. I
think this about where I got to in the Alpaca before I stopped having
free time to spend furthering my Perl education.

I did think of putting the sub contents in a BEGIN block, and lose it at
the end of the program, but I don't think that's very elegant (and I'm
not certain I could make that work either). Is there another way, or do
I have to put up with it how it is?

   Justin.

-- 
Justin C, by the sea.


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

Date: Tue, 19 Apr 2011 11:10:30 -0700
From: Jim Gibson <jimsgibson@gmail.com>
Subject: Re: Spreadsheet::WriteExcel, can't write to returned object?
Message-Id: <190420111110305427%jimsgibson@gmail.com>

In article <cim088-vlu.ln1@zem.masonsmusic.co.uk>, Justin C
<justin.1104@purestblue.com> wrote:

> $deity knows if I've got the terminology right on this. I'm trying to
> tidy up an old program that extracts some stuff from one Excel
> spreadsheet, munges it a little, and then puts it into another
> spreadsheet. My method of tidying is, in this instance, to take all of
> the bits and put them into subroutines so that the main program looks a
> lot cleaner.
> 
> So I *had*:
> #!/usr/bin/perl
> 
> use strict;
> use warnings;
> use Spreadsheet::WriteExcel;
> 
> my $file = 'delete_me.xls';
> my $workbook = Spreadsheet::WriteExcel->new($file);
> my $excel = $workbook->add_worksheet();
> 
> for my $row ( 0 .. 99 ) {
>   for my $col ( 0 .. 9 ) {
>     my $str = $row * $col;
>     $excel->write_string($row, $col, $str);
>   }
> }
> 
> That works as expected. I wanted to 'tidy away' the creation of the file and
> worksheet (I've also got some formatting coding there too in my real
> program). So here's what I made:
> 
> #!/usr/bin/perl
> 
> use strict;
> use warnings;
> use Spreadsheet::WriteExcel;
> 
> my $file = 'delete_me.xls';
> my $excel = create_excel_file($file);
> 
> for my $row ( 0 .. 99 ) {
>   for my $col ( 0 .. 9 ) {
>     my $str = $row * $col;
>     $excel->write_string($row, $col, $str);
>   }
> }
> 
> sub create_excel_file {
>   my $of = shift;
>   my $workbook = Spreadsheet::WriteExcel->new($of);
>   my $worksheet = $workbook->add_worksheet();
>   return $worksheet;
> }
> 
> This creates an empty file, the returned worksheet object doesn't get
> anything printed to it, nor do I get any errors or warnings. I tried
> returning \$worksheet but then the $exel->write_string line complained
> "Can't call method ... on an unblessed reference".
> 
> This is probably where we see gaping holes in my Perl understanding. I
> think this about where I got to in the Alpaca before I stopped having
> free time to spend furthering my Perl education.

The problem is that the top-level spreadsheet object ($workbook) as
returned by new() is lexically-scoped to the create_excel_file
subroutine and goes out of scope when the subroutine returns. While you
are returning and saving the worksheet object, the spreadsheet file has
probably been closed and written to disk at that point, so further
writes do not get saved.

Solutions are to either 1) return the workbook object as well or 2)
make the workbook object global (file scope).

-- 
Jim Gibson


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

Date: Tue, 19 Apr 2011 07:46:58 -0500
From: Tad McClellan <tadmc@seesig.invalid>
Subject: Re: to eval or not to eval?
Message-Id: <slrniqr0p6.nse.tadmc@tadbox.sbcglobal.net>

Marc Girod <marc.girod@gmail.com> wrote:
> Hello,
>
> I am trying to eval metacode in a context, and cannot hide the
> context.
>
> -8<-------
> #!/usr/bin/perl -w
>
> use strict;
> my $fubar = q(my $foo = 'bar';);
>
> print eval "$fubar\n";


Here you tell perl to print the return value from eval.

If you don't want to print the return value, then:

    eval "$fubar\n";
or
    eval $fubar;


> while (<DATA>) {
>   print eval "${fubar}qq($_)";
> }
> print "End\n";
> __DATA__
> Hello ${foo}!
> -8<-------
>
> This gives me:
>
> ~> ./tmp/evtst
> barHello bar!
> End
>
> The first 'bar' there is what annoys me... Go away!


If you don't want to print something, then don't print it!


> But why is it there?


Because you told it to be there.


> Yes: it is returned by the assignment to/initialization of $foo...


 ... which in turn is an argument to print().


> Why is it part of the return of 'eval'?

    perldoc -f eval

says:

    the value returned is the value of the last expression evaluated


So your question seems to be:

    Why did print() print its arguments?

:-)



-- 
Tad McClellan
email: perl -le "print scalar reverse qq/moc.liamg\100cm.j.dat/"
The above message is a Usenet post.
I don't recall having given anyone permission to use it on a Web site.


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

Date: Tue, 19 Apr 2011 06:07:58 -0700 (PDT)
From: Marc Girod <marc.girod@gmail.com>
Subject: Re: to eval or not to eval?
Message-Id: <499b62fb-e62a-42ab-b694-243a03ba4518@z37g2000vbl.googlegroups.com>

On Apr 19, 1:46=A0pm, Tad McClellan <ta...@seesig.invalid> wrote:

> =A0 =A0 the value returned is the value of the last expression evaluated

That's what I thought.
So, what I miss is what is 'last expression evaluated' in: 1;2;
I expected it would be: 2

~> perl -le 'print eval "1;2;"'
2

Why does eval return the result of the *first* expression as well?
This is (still) my question.
Thanks,
Marc


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

Date: Tue, 19 Apr 2011 06:13:51 -0700 (PDT)
From: Marc Girod <marc.girod@gmail.com>
Subject: Re: to eval or not to eval?
Message-Id: <2ccabc35-2676-4d98-9f9f-4960e30b62cc@z33g2000vbk.googlegroups.com>

On Apr 19, 1:46=A0pm, Tad McClellan <ta...@seesig.invalid> wrote:

> > print eval "$fubar\n";

Oops... What does this do there?

I thought I had removed that line!
Thanks for pointing it.
Sorry.

Marc


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

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


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