[29001] in Perl-Users-Digest

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

Perl-Users Digest, Issue: 245 Volume: 11

daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Tue Mar 20 21:09:42 2007

Date: Tue, 20 Mar 2007 18:09:07 -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, 20 Mar 2007     Volume: 11 Number: 245

Today's topics:
    Re: "Casting" a split into an array <wyzelli@yahoo.com>
    Re: checking for filehandle anno4000@radom.zrz.tu-berlin.de
    Re: eq and =? problem? Geoff Cox
    Re: Need help understanding how a file input block work <someone@example.com>
    Re: Need help understanding how a file input block work <ben@morrow.me.uk>
    Re: Need help understanding how a file input block work <tadmc@augustmail.com>
    Re: Need help understanding how a file input block work <ben@morrow.me.uk>
    Re: perl: adding lines and replacing stings <tadmc@augustmail.com>
        Problem with flock <fred4414@nethere.com>
    Re: Server/Clients system <deadpickle@gmail.com>
        Digest Administrivia (Last modified: 6 Apr 01) (Perl-Users-Digest Admin)

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

Date: Tue, 20 Mar 2007 22:57:09 GMT
From: "Peter Wyzl" <wyzelli@yahoo.com>
Subject: Re: "Casting" a split into an array
Message-Id: <9FZLh.13975$8U4.2938@news-server.bigpond.net.au>

"Fabrice Baro" <fabrice.baro@gmail.com> wrote in message 
news:1174402146.567952.111460@d57g2000hsg.googlegroups.com...
>> the reason I do this is to be able to access each letter by index 
>> C++-style
> I want to randomly select a certain number of letters among my
> string.
> I'm planning to shuffle an index and pick the desired number of
> letters.
>
> Original:
> 0 1 2 3 4 5 <- index
> L G R D T I <- letters
>
> Shuffle:
> 4 2 5 1 0 3
> T R I G
>      ^
>      Pick until here
>
> Does anyone see a better way ?

"Fabrice Baro" <fabrice.baro@gmail.com> wrote in message
news:1174402146.567952.111460@d57g2000hsg.googlegroups.com...
>> the reason I do this is to be able to access each letter by index
>> C++-style
> I want to randomly select a certain number of letters among my
> string.
> I'm planning to shuffle an index and pick the desired number of
> letters.
>
> Original:
> 0 1 2 3 4 5 <- index
> L G R D T I <- letters
>
> Shuffle:
> 4 2 5 1 0 3
> T R I G
>      ^
>      Pick until here

What is the condition that determines where 'here' is? Is it the same each
time or is it different based on some condition? (i.e. until a specific
letter is found? Or x number of letters?)

Why build an array, and an array of the indexes when you can just shuffle
the array and then step through the indexes until you meet the above
condition?  Is there some reason the array of letters needs to preserve it's
order (which can't be met by preserving the pre-split sting?)?

Shuffling an array is a FAQ....  So maybe your answers to the two above
questions will help you a little...

Modified from PerlFAQ4

my $string = 'abcdefghijklmnopqrstuvwxyz';
my @letters = split //, $string;
fisher_yates_shuffle( \@letters ); # randomize @letters in place
print @letters;


sub fisher_yates_shuffle {
    my $deck = shift; # $deck is a reference to the array
    my $i = @$deck;
    while ($i--) {
        my $j = int rand ($i+1);
        @$deck[$i,$j] = @$deck[$j,$i];
    }
}


In this array the indexes remain sequential and any letter can be accessed
directly by $letters[$arrayindex]...



I hope I'm not completely on the wrong track...

P

-- 




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

Date: 20 Mar 2007 22:49:10 GMT
From: anno4000@radom.zrz.tu-berlin.de
Subject: Re: checking for filehandle
Message-Id: <56b6n6F288ap4U1@mid.dfncis.de>

Ben Morrow  <ben@morrow.me.uk> wrote in comp.lang.perl.misc:
> 
> Quoth anno4000@radom.zrz.tu-berlin.de:
> > Yakov <iler.ml@gmail.com> wrote in comp.lang.perl.misc:
> > > On Mar 19, 7:23 am, anno4...@radom.zrz.tu-berlin.de wrote:
> > > > Yakov <iler...@gmail.com> wrote in comp.lang.perl.misc:
> > > >
> > > > > Let's say I want to check whether $fh is a filehandle. Take 1
> > > > > is to: defined(fileno($fh)). Perfect solution ? No. When $fh is a
> > > > > tied-filehandle, $fh may not have real filedescriptor behind it
> > > > > ( for example, it sends output to the shared memory ).
> > > >
> > > > > How do I check for $fh being a  filehandle, the check  would work
> > > > > even for tied filehandles  that do not have real filedescriptor ?
> > > >
> > > > In general it is hard to say for sure what a tied variable will respond
> > > > to.  You can use tied() to access the underlying object and make
> > > > plausibility tests:
> > > >
> > > >     my $is_fh = tied( $h) && tied( $h)->isa( 'File::Handle');
> > > >
> > > > or
> > > >
> > > >     my $is_fh = tied( $h) && tied( $h)->can( 'READ');
> > > >
> > > > or similar.  Both can go wrong, but will give the correct answer in most
> > > > cases.
> > > 
> > > Ok thanks. This seems to be the check:
> > > 
> > >    defined(fileno($fh)) || (tied( $fh) && tied($fh)-
> > > >can( 'TIEHANDLE' ))
> > > 
> > > Looks ok ?
> > 
> > Yes.  In fact, testing for "TIEHANDLE" should be pretty much watertight.
> 
> Not at all. Consider:

[consideration of false positives snipped]

You are right, I wasn't thinking of false positives at all.  

> The correct answer is Scalar::Util::openhandle.

Thanks for pointing it out.  I hadn't noticed this one, but
Scalar::Util is full of tests that you don't use every day,
but are hard to get right when you need them.

blessed, isweak, isvstring, looks_like_number, openhandle,
readonly, reftype, tainted are all more or less in that category.

Anno

Anno


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

Date: Tue, 20 Mar 2007 23:33:42 +0000
From: Geoff Cox
Subject: Re: eq and =? problem?
Message-Id: <4qr003p2g9g2a4pjk06o1g8s1cqh6ponfj@4ax.com>

On Tue, 20 Mar 2007 21:54:51 +0100, Adrian Ulrich
<adrian_200503@blinkenlights.ch> wrote:

>> I found a solution by changing the bp to bisplans to avoid any
>> confusion between bp and bplann.
>
>Maybe something adds some weird/unwanded chars to $path
>
>print unpack("H*", $path)."\n";
>
>should display them.
> 
>
>> How did you test out the code I posted?!
>
>#!/usr/bin/perl
>use strict;
>my $path = "docs/applied-business/as/classroom-notes/edexcel/unit2/bplanning";
>if ( $path eq "docs/applied-business/as/classroom-notes/edexcel/unit2/bp" ) {
>	die "1\n";
>}
>elsif ( $path eq "docs/applied-business/as/classroom-notes/edexcel/unit2/bplanning" ) {
>	die "2\n";
>}
>else {
>	die "3\n";
>}


Thanks Adrian - will give that a go.

Cheers

Geoff


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

Date: Tue, 20 Mar 2007 22:40:08 GMT
From: "John W. Krahn" <someone@example.com>
Subject: Re: Need help understanding how a file input block works
Message-Id: <cpZLh.112397$Du6.91992@edtnps82>

Paul wrote:
> Hello there.  Please forgive this newbie question but I don't really
> know Perl as I have only been using it for a few days.
> 
> I need to understand how a particular script works and am having
> difficulty with one particular subroutine.
> First, here is a sample of the input file (IN_FILE):
> ---
> OVERVIEW
> ----------------------------
> This is where notes and stuff goes.
> And maybe some more notes here too.
> 
> MATERIALS
> ----------------------------
> This is where more notes and stuff goes.
> 
> etc...
> ---
> 
> Second, here is a section of the Perl code that I am having
> difficulties with:
> ---
> sub parsefile
> {
> 1: $overview=0; @overview = ();
> 2: # open file..
> 3: while ($line = <IN_FILE>)
> 4: {
> 5: 	if ($line =~ /^\U\w*/)
> 6: 	{
> 7:		if ($line =~ /^OVERVIEW/)
> 8:		{
> 9:			$line = <IN_FILE>; next if $line !~ /--------+/;
> 10:			if ($overview== 1) {error("More than one Overview section")}
> 11:			$overview++;
> 12:			$bin = \@overview;
> 13:			next;
> 14:		}
> 15:	}
> 16:	$line =~ s/\"/\'/g;
> 17:	push (@$bin,$line);
> 18: }
> 19: if (!$overview) {error("Missing a Overview section")}
> 20: # etc...
> }
> ---
> 
> So here's what I've figured out so far:
> 
> - line 3 starts a loop that goes through each line in the input file

Correct so far.

> - line 5 I had difficulties with, but I think it means "if the line
> starts with an uppercase word char" then do this block

$ perl -le'my $pattern = qr/^\U\w*/; print $pattern'
(?-xism:^\W*)

So the expression:

> 5: 	if ($line =~ /^\U\w*/)

Is the same as:

> 5: 	if ($line =~ /^\W*/)

Which says match if the line begins with zero or more *non-word* characters
and since *every* line begins with zero non-word characters then every line
will match.  In other words, this test does nothing useful.

> - line 7 says "if the line starts with 'OVERVIEW'" then do this block

Correct.

> (Here's where I start to lose it. I think I might be having
> difficulties with the 'block' concept.. but let me continue..)
> 
> - line 9 starts by saying 'get the next line in the input file.
> *Then* it says "next if" the line doesn't contain a bunch of dashes.

Correct.

> QUESTION 1: Where does "next" go?  Does it go to the start of line 9
> (i.e. the beginning of the current block) or to line 3?

next goes to the beginning of the enclosing loop and there is only one loop in
your example.

> - line 10 is an error check and calls some other method.  (I'm okay
> with this line.)
> - line 11 increments the $overview count.  ok.
> 
> - line 12 --> I HAVE NO IDEA!
> 
> QUESTION 2: What does line 12 do?  Does it assign something to a
> variable?  If so, I don't get it.  at all.

It assigns a reference of the array @overview to the scalar $bin.  I have no
idea why this is being done because the code is always referencing the same array.

> - line 13 - "next" to where?  Line 3?

Again, there is only one loop that 'next' can apply to.

> - line 16 does a double-quote substitution. ok.
> 
> - line 17 pushes the content of the $line into .. what *is* that
> variable?  where did it come from?  (It's not used anywhere else in
> the script!)
> 
> QUESTION 3: What is this variable in line 17?

That is the variable that was assigned to on line 12.  The reference in $bin
is dereferenced and so the original array @overview has a value pushed onto it.




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


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

Date: Tue, 20 Mar 2007 23:44:44 +0000
From: Ben Morrow <ben@morrow.me.uk>
Subject: Re: Need help understanding how a file input block works
Message-Id: <c886d4-pbe.ln1@osiris.mauzo.dyndns.org>


Quoth "Paul" <tester.paul@gmail.com>:
> Hello there.  Please forgive this newbie question but I don't really
> know Perl as I have only been using it for a few days.

Firstly: thank you for your clear problem description :).

> I need to understand how a particular script works and am having
> difficulty with one particular subroutine.
> First, here is a sample of the input file (IN_FILE):
> ---
> OVERVIEW
> ----------------------------
> This is where notes and stuff goes.
> And maybe some more notes here too.
> 
> MATERIALS
> ----------------------------
> This is where more notes and stuff goes.
> 
> etc...
> ---
> 
> Second, here is a section of the Perl code that I am having
> difficulties with:

There are several stylistic and code-hygiene issues with this code; I
will deal with them below, after your 'real' questions.

> ---
> sub parsefile
> {
> 1: $overview=0; @overview = ();
> 2: # open file..
> 3: while ($line = <IN_FILE>)
> 4: {
> 5: 	if ($line =~ /^\U\w*/)
> 6: 	{
> 7:		if ($line =~ /^OVERVIEW/)
> 8:		{
> 9:			$line = <IN_FILE>; next if $line !~ /--------+/;
> 10:			if ($overview== 1) {error("More than one Overview section")}
> 11:			$overview++;
> 12:			$bin = \@overview;
> 13:			next;
> 14:		}
> 15:	}
> 16:	$line =~ s/\"/\'/g;
> 17:	push (@$bin,$line);
> 18: }
> 19: if (!$overview) {error("Missing a Overview section")}
> 20: # etc...
> }
> ---
> 
> So here's what I've figured out so far:
> 
> - line 3 starts a loop that goes through each line in the input file
> - line 5 I had difficulties with, but I think it means "if the line
> starts with an uppercase word char" then do this block

Pretty much. $line =~ /.../ is an expression that is 'true'[0] if the
contents of $line match the pattern ('regular expression' or 'regex')
between the slashes. A tutorial for Perl's regexen is available in
'perldoc perlretut'; the full description is in 'perldoc perlre'. Your
pattern has four parts:

    ^   says 'match if we are at the start of the string',
    \U  is an error, see below,
    \w  says 'match any word character', which for various reasons means
        'any letter (upper- or lowercase), any digit, or _',
    *   says 'allow the preceding item to match zero or more times'.

[0] I'm assuming you know enough about programming in general to be
familiar with the idea of expressions being 'true' or 'false', and
constructions like 'if' that test that.

The original author presumably thought /\U/ meant 'match any uppercase
letter', but that is not the case. It *actually* means 'before
attempting to match this pattern, take everything from here to the next
\E and make it uppercase'. So the pattern actually being matched is
/^\W*/, which means 'the start of the string, followed by zero-or-more
characters which are *not* word characters'. This will match anything at
all, as the only non-optional part is 'the start of the string', and
every string has a start :).

What the author meant, instead of /\U/, was /[[:upper:]]/. This means

    [...]       match any one of the characters inside the brackets
    [:upper:]   insert a list of all uppercase characters. Note that
                this only works inside [...].

So, your pattern (once fixed) will match strings like 'OVERVIEW', but
also strings like 'Overview' and 'Xfff_8885'; and, since you don't
insist the match goes all the way to the end of the string, 'U %#@:'.
Note that the /\w*/ part is completely useless, as it is allowed to
match nothing at all and nothing follows it. I suspect you probably want
something more like /^[[:upper:]]+$/, which means

    ^           the start of the string
    [[:upper:]] any uppercase character...
    +           ...one or more times
    $           the end of the string

If you want to allow spaces in the string you need something like
/^[[:upper:]\s]+$/, where \s means 'match any space character'.

> - line 7 says "if the line starts with 'OVERVIEW'" then do this block

Yup.

> (Here's where I start to lose it. I think I might be having
> difficulties with the 'block' concept.. but let me continue..)
> 
> - line 9 starts by saying 'get the next line in the input file.
> *Then* it says "next if" the line doesn't contain a bunch of dashes.
> 
> QUESTION 1: Where does "next" go?  Does it go to the start of line 9
> (i.e. the beginning of the current block) or to line 3?

'next' is documented in perldoc perl, in the sextion "Loop Control".
What it means is 'start the next iteration of the innermost loop'. In
this case, the innermost loop is the 'while' loop that begins on line 3,
so that's where it goes. Note that it doesn't just jump up to line 3:
that would be 'redo', which restarts the current iteration. It
re-evaluates the '$line = <IN_FILE>' expression first, getting another
line from the file or ending the loop if there aren't any more.

> - line 10 is an error check and calls some other method.  (I'm okay
> with this line.)
> - line 11 increments the $overview count.  ok.
> 
> - line 12 --> I HAVE NO IDEA!
> 
> QUESTION 2: What does line 12 do?  Does it assign something to a
> variable?  If so, I don't get it.  at all.

line 12 says 'take a reference to the variable @overview, and assign it
to $bin'. Understanding the concept of references (or 'pointers' in C)
is crucial to any more than basic programming. I would strongly
recommend you read through the whole of perldoc perlreftut, which is a
decent introduction to the idea. (If it *isn't*, please let us know
which bits you don't understand, so we can fix them :).)

> - line 13 - "next" to where?  Line 3?

Yup: again, the innermost loop.

> - line 16 does a double-quote substitution. ok.
>
> - line 17 pushes the content of the $line into .. what *is* that
> variable?  where did it come from?  (It's not used anywhere else in
> the script!)
> 
> QUESTION 3: What is this variable in line 17?

It's not a variable :). It's a dereference expression. It has two parts:
'$bin' is a normal scalar variable, and '@' as a prefix is the array
deref operator, and says 'find the array that this reference refers to':
in this case the @overview array (because of line 12). Again, read
perlreftut.

> Finally, somewhere along the line I think the @overview array is
> assigned the content of each of the lines between the heading rows.
> But I'm not sure how that's done.  I'm pretty sure it happens in the
> block above, but there's some kind of voodoo magic working that is
> keeping me from seeing it.

It's the reference stuff that's confused you.

So, some more general comments. I'll include the original again, so you
can see what I'm talking about.

> sub parsefile
> {

This is an unimportant stylistic matter, but it is usual in Perl to put
an opening brace at the end of the line:

    sub parsefile {

> 1: $overview=0; @overview = ();

These two are global variables. Globals are best avoided: if some other
part of your program uses $overview, it could interfere with this sub,
causing a very hard-to-find bug. You should *always* begin your programs
with

    use strict;

which will stop you from using globals by accident. Next you should
*always* have

    use warnings;

which will warn you about potential problems. Adding 'use strict;' to
this program will likely produce a whole lot of errors about 'Global
symbol $foo requires explicit package name': this is telling you you
have an undeclared global. You can fix these by putting

    my $foo;

*just* before you need the variable: this creates a $foo that only
exists in this part of the program, so noone else can interfere with it.
See perldoc perlsub, the section called "Private Variables via my()",
and also http://perl.plover.com/FAQs/Namespaces.html .

In this case, you need the 'my' up here, outside the loop; otherwise
you'll get a fresh copy every time the loop goes around. You don't need
them until just before the loop, though, so they can go below opening
the file.

Variables in Perl are always initialized: arrays and hashes to 'empty',
scalars to the special value undef, that behaves like 0 when treated as
a number and like '' when treated as a string. These two initializations
are probably a poor attempt to compensate for the fact the author wasn't
using proper 'my' variables: you don't need them.

> 2: # open file..
> 3: while ($line = <IN_FILE>)

This filehandle (IN_FILE) is also global. You don't specify how you're
opening it, but I presume it's something like

    open IN_FILE, 'foo' or die "can't open 'foo': $!";

(You *do* check you could open it, don't you? And you *do* include the
reason it couldn't be opened, which can be found in the magic $!
variable?)

This should be replaced with

    open my $IN_FILE, '<', 'foo'
        or die "can't open 'foo': $!";

This has two differences: firstly, the filehandle is placed in a new
'my' variable, so it's no longer global; and secondly, you're explicitly
telling Perl you want to open the file for reading. This isn't so
important in this case, but get into the habit of doing it now, or one
day you'll write something like

    open my $FILE, $filename or die "...";

, some malicious person will manage to make $filename contain 
'|rm -rf /', and all you're files will be deleted. Perl's 'magic open'
is terribly flexible, but rather dangerous.

The while loop then needs to become

    while (my $line = <$IN_FILE>) {

so that $line is declared, of course.

> 4: {
> 5: 	if ($line =~ /^\U\w*/)

As discussed above, this regex matches everything, so this whole 'if'
block is completely useless.

> 6: 	{
> 7:		if ($line =~ /^OVERVIEW/)
> 8:		{
> 9:			$line = <IN_FILE>; next if $line !~ /--------+/;
> 10:			if ($overview== 1) {error("More than one Overview 
    section")}

    if ($overview) { 

would be more consistent with what comes below. Also, stylistically,
writing an if all bunched up like that is horrid. 

    if ($overview) {
        error(...);
    }

> 11:			$overview++;
> 12:			$bin = \@overview;

This line I don't understand the purpose of. Is $bin assigned a ref to
some other array earlier in the program? If not, then the program will
crash unless the first line in the file is an OVERVIEW section, as the
deref below will have nothing to deref; and the whole exercise is
pointless, as you can just push onto the @overview array directly.

> 13:			next;
> 14:		}
> 15:	}
> 16:	$line =~ s/\"/\'/g;

The backslashes are both unnecessary.

    $line =~ s/"/'/g;

This would be clearer and faster with tr///:

    $line =~ tr/"/'/;

Ben

-- 
  The cosmos, at best, is like a rubbish heap scattered at random.
                                                           Heraclitus
  ben@morrow.me.uk


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

Date: Tue, 20 Mar 2007 18:55:26 -0500
From: Tad McClellan <tadmc@augustmail.com>
Subject: Re: Need help understanding how a file input block works
Message-Id: <slrnf00t3e.s6n.tadmc@tadmc30.august.net>

Paul <tester.paul@gmail.com> wrote:
> Hello there.  Please forgive this newbie question but I don't really
> know Perl as I have only been using it for a few days.
>
> I need to understand how a particular script works

> sub parsefile
> {
> 1: $overview=0; @overview = ();
> 2: # open file..
> 3: while ($line = <IN_FILE>)
> 4: {
> 5: 	if ($line =~ /^\U\w*/)
> 6: 	{
> 7:		if ($line =~ /^OVERVIEW/)
> 8:		{
> 9:			$line = <IN_FILE>; next if $line !~ /--------+/;
> 10:			if ($overview== 1) {error("More than one Overview section")}
> 11:			$overview++;
> 12:			$bin = \@overview;
> 13:			next;
> 14:		}
> 15:	}
> 16:	$line =~ s/\"/\'/g;
> 17:	push (@$bin,$line);
> 18: }
> 19: if (!$overview) {error("Missing a Overview section")}
> 20: # etc...
> }


Whoever wrote this code did not know Perl very well either...


> QUESTION 1: Where does "next" go?  


It goes where the documentation for the next operator says it will go.  :-)

   perldoc -f next

       next LABEL
       next    The "next" command is like the "continue" statement in C; it
               starts the next iteration of the loop:


> Does it go to the start of line 9
> (i.e. the beginning of the current block) or to line 3?


It goes to the beginning of the _loop_ containing the next, 
line 3 in this case.


> - line 12 --> I HAVE NO IDEA!
> QUESTION 2: What does line 12 do?  Does it assign something to a
> variable?  If so, I don't get it.  at all.


It is taking a reference to an array:

   perldoc perlreftut



> - line 13 - "next" to where?  Line 3?


Yes.


> - line 16 does a double-quote substitution. ok.


Though it does illustrate that this programmer didn't really know
much Perl. Double quotes are not meta in regexes, and single quotes
are not meta in strings, so neither needs to be backslashed:

   $line =~ s/"/'/g;

And even better way would be:

   $line =~ tr/"/'/;


> - line 17 pushes the content of the $line into .. what *is* that
> variable?  


It is dereferencing the reference that it took earlier.


> where did it come from?  (It's not used anywhere else in
> the script!)


$bin is. The at-sign is dereferencing $bin as an array.


-- 
    Tad McClellan                          SGML consulting
    tadmc@augustmail.com                   Perl programming
    Fort Worth, Texas


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

Date: Wed, 21 Mar 2007 00:09:29 +0000
From: Ben Morrow <ben@morrow.me.uk>
Subject: Re: Need help understanding how a file input block works
Message-Id: <pm96d4-pge.ln1@osiris.mauzo.dyndns.org>


Quoth Ben Morrow <ben@morrow.me.uk>:
> 
> Quoth "Paul" <tester.paul@gmail.com>:
> > Hello there.  Please forgive this newbie question but I don't really
> > know Perl as I have only been using it for a few days.
> 
> Firstly: thank you for your clear problem description :).
> 
> > I need to understand how a particular script works and am having
> > difficulty with one particular subroutine.
> > First, here is a sample of the input file (IN_FILE):
> > ---
> > OVERVIEW
> > ----------------------------
> > This is where notes and stuff goes.
> > And maybe some more notes here too.
> > 
> > MATERIALS
> > ----------------------------
> > This is where more notes and stuff goes.
> > 
> > etc...
> > ---
> > 
> > Second, here is a section of the Perl code that I am having
> > difficulties with:
> 
> There are several stylistic and code-hygiene issues with this code; I
> will deal with them below, after your 'real' questions.
> 
> > ---
> > sub parsefile
> > {
> > 1: $overview=0; @overview = ();
> > 2: # open file..
> > 3: while ($line = <IN_FILE>)
> > 4: {
> > 5: 	if ($line =~ /^\U\w*/)
> > 6: 	{
> > 7:		if ($line =~ /^OVERVIEW/)
> > 8:		{
> > 9:			$line = <IN_FILE>; next if $line !~ /--------+/;
> > 10:			if ($overview== 1) {error("More than one Overview section")}
> > 11:			$overview++;
> > 12:			$bin = \@overview;
> > 13:			next;
> > 14:		}
> > 15:	}
> > 16:	$line =~ s/\"/\'/g;
> > 17:	push (@$bin,$line);
> > 18: }
> > 19: if (!$overview) {error("Missing a Overview section")}
> > 20: # etc...
> > }
> > ---
> > 
> > So here's what I've figured out so far:
> > 
> > - line 3 starts a loop that goes through each line in the input file
> > - line 5 I had difficulties with, but I think it means "if the line
> > starts with an uppercase word char" then do this block
> 
> Pretty much. $line =~ /.../ is an expression that is 'true'[0] if the
> contents of $line match the pattern ('regular expression' or 'regex')
> between the slashes. A tutorial for Perl's regexen is available in
> 'perldoc perlretut'; the full description is in 'perldoc perlre'. Your
> pattern has four parts:
> 
>     ^   says 'match if we are at the start of the string',
>     \U  is an error, see below,
>     \w  says 'match any word character', which for various reasons means
>         'any letter (upper- or lowercase), any digit, or _',
>     *   says 'allow the preceding item to match zero or more times'.
> 
> [0] I'm assuming you know enough about programming in general to be
> familiar with the idea of expressions being 'true' or 'false', and
> constructions like 'if' that test that.
> 
> The original author presumably thought /\U/ meant 'match any uppercase
> letter', but that is not the case. It *actually* means 'before
> attempting to match this pattern, take everything from here to the next
> \E and make it uppercase'. So the pattern actually being matched is
> /^\W*/, which means 'the start of the string, followed by zero-or-more
> characters which are *not* word characters'. This will match anything at
> all, as the only non-optional part is 'the start of the string', and
> every string has a start :).
> 
> What the author meant, instead of /\U/, was /[[:upper:]]/. This means
> 
>     [...]       match any one of the characters inside the brackets
>     [:upper:]   insert a list of all uppercase characters. Note that
>                 this only works inside [...].
> 
> So, your pattern (once fixed) will match strings like 'OVERVIEW', but
> also strings like 'Overview' and 'Xfff_8885'; and, since you don't
> insist the match goes all the way to the end of the string, 'U %#@:'.
> Note that the /\w*/ part is completely useless, as it is allowed to
> match nothing at all and nothing follows it. I suspect you probably want
> something more like /^[[:upper:]]+$/, which means
> 
>     ^           the start of the string
>     [[:upper:]] any uppercase character...
>     +           ...one or more times
>     $           the end of the string
> 
> If you want to allow spaces in the string you need something like
> /^[[:upper:]\s]+$/, where \s means 'match any space character'.
> 
> > - line 7 says "if the line starts with 'OVERVIEW'" then do this block
> 
> Yup.
> 
> > (Here's where I start to lose it. I think I might be having
> > difficulties with the 'block' concept.. but let me continue..)
> > 
> > - line 9 starts by saying 'get the next line in the input file.
> > *Then* it says "next if" the line doesn't contain a bunch of dashes.
> > 
> > QUESTION 1: Where does "next" go?  Does it go to the start of line 9
> > (i.e. the beginning of the current block) or to line 3?
> 
> 'next' is documented in perldoc perl, in the sextion "Loop Control".

I meant

    perldoc perlsyn, in the section "Loop Control"

of course.

Ben

-- 
                Outside of a dog, a book is a man's best friend.
                Inside of a dog, it's too dark to read.
ben@morrow.me.uk                                                  Groucho Marx


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

Date: Tue, 20 Mar 2007 18:38:16 -0500
From: Tad McClellan <tadmc@augustmail.com>
Subject: Re: perl: adding lines and replacing stings
Message-Id: <slrnf00s38.s6n.tadmc@tadmc30.august.net>

Ben Morrow <ben@morrow.me.uk> wrote:
>
> Quoth "Paul Lalli" <mritty@gmail.com>:
>> On Mar 20, 12:29 pm, Ben Morrow <b...@morrow.me.uk> wrote:
>> > Quoth "erobinson32" <samdani...@gmail.com>:
>> >
>> > > I would like to do three things in a single Perl script:
>> > > 1. Add the text "FirstLine" to the very first line of a sample file.
>> > > 2. Add the test "LastLine" to the very last line of a sample file.
>> > > 3. Replace all of the instances of 'California' to 'Nevada' in a file.
>> >
>> > You're nearly there :)
>> >
>> > perl -pi -le'
>> >     BEGIN { print "FirstLine" }
>> >     s/California/Nevada/g;
>> >     END { print "LastLine" }'
>> >
>> 
>> Uhm, you're not, unfortunately. :-P  Did you actually try this?
>
> Well, clearly not. Sorry about that :(.
>
>> The -i feature takes affect only during the while(<>) {} loop created
>> by -p, and BEGIN{} and END{} blocks happen outside that loop.  End
>> result - the two blocks print to STDOUT rather than the file.
>
> Yes, of course... and there I thought I was being so clever :(. Ach
> well.


But at least you took the heat that I would have gotten, as I was
going to suggest the same thing.  :-)


-- 
    Tad McClellan                          SGML consulting
    tadmc@augustmail.com                   Perl programming
    Fort Worth, Texas


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

Date: Tue, 20 Mar 2007 17:41:56 -0700
From: Fred Hare <fred4414@nethere.com>
Subject: Problem with flock
Message-Id: <z9-dnTH62P3K4p3bnZ2dnUVZ8qqlnZ2d@giganews.com>

Using Perl 5.6 and WinXP-SP2
I have .eml newsgroup files from Seamonkey 1.1 which stay locked even 
when I close mail&news. I use Perl to rename and clean the .eml files, 
but this fails when they are locked by SM.

I tried to unlock the .eml files using flock, but I get the error
"can't unlock D:\aa\locked.eml:
    Unknown error at D:\aa\unlock.pl line 12."

And if I try to lock an unlocked file (as test), I get no error, but the 
file stays unlocked.


use strict ;
use warnings ;
use Fcntl qw(:DEFAULT :flock);

  my $nl = 'D:\aa\NotLocked.txt' ;
  open my $FH1, '<', $nl or die "Could not open $nl for reading: $!\n";
  flock($FH1, LOCK_SH) or die "can't lock $nl: $!";  # This is line 12
  close $FH1 ;

  my $file = 'D:\aa\locked.eml' ;
  open my $FH, '<', $file or die "Could not open $file for read: $!\n";
  flock ($FH,LOCK_UN) or die "can't unlock $file: $!";
  close $FH ;

__END__


-- 
Fred

When using my email address, add the word "Trustme" anywhere on the 
subject-line. Otherwise the message will be deleted on the server.


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

Date: 20 Mar 2007 17:06:13 -0700
From: "deadpickle" <deadpickle@gmail.com>
Subject: Re: Server/Clients system
Message-Id: <1174435573.070050.306180@n76g2000hsh.googlegroups.com>

On Mar 20, 2:10 pm, "deadpickle" <deadpic...@gmail.com> wrote:
> On Mar 20, 2:05 pm, "deadpickle" <deadpic...@gmail.com> wrote:
>
>
>
> > On Mar 20, 1:48 pm, "Peter J. Holzer" <hjp-usen...@hjp.at> wrote:
>
> > > On 2007-03-20 17:20, deadpickle <deadpic...@gmail.com> wrote:
>
> > > > On Mar 20, 9:23 am, Ted Zlatanov <t...@lifelogs.com> wrote:
> > > >> On 20 Mar 2007 07:04:30 -0700 "deadpickle" <deadpic...@gmail.com> wrote:
> > > >> d> First of all I havent wrote any code for this yet, I'm still in the
> > > >> d> brainstorming section. What I want to do is have a server that resides
> > > >> d> on a networked computer somewhere. This server will recieve files from
> > > >> d> 2 clients. Then these 2 clients will ask the server for another file
> > > >> d> and the server will send it. So in summary I have 2 Clients that can
> > > >> d> send and recieve files and a Server that can recieve and send files.
> > > >> d> Hope that makes sense. I am not sure on how to do this, or how to get
> > > >> d> started, anyone got any ideas?
>
> > > >> Well, you could implement this with FTP or HTTP (HTTP has a "PUT"
> > > >> command), reimplementing as much of the protocol as you desire.  Are
> > > >> you trying to implement something new as a fun project, or is this
> > > >> real work?  In the real world I'd avoid writing new protocols when so
> > > >> many good ones exist already (implemented in C, bug-free, etc.).
> > > [...]
> > > >  This is for a undergraduate project at my university. I'm thinking
> > > > about using BitTorrent. I want this whole system to be autonomous and
> > > > to make many transfers every minute, can BitTorrent do this?
>
> > > BitTorrent doesn't sound like a good choice: Firstly, it doesn't have an
> > > upload capability (AFAIK). Secondly, it isn't designed to transfer many
> > > small files between a server and a small number of clients - it is
> > > designed to distribute large files to to a large number of clients.
>
> > > Writing a bittorrent implementation might be fun and instructive, but
> > > for your (stated) needs it sounds like overkill. HTTP is probably the
> > > simplest protocol for that purpose (as long as you don't implement all
> > > of RFC 2616).
>
> > >         hp
>
> > > --
> > >    _  | Peter J. Holzer    | Blaming Perl for the inability of programmers
> > > |_|_) | Sysadmin WSR       | to write clearly is like blaming English for
> > > | |   | h...@hjp.at         | the circumlocutions of bureaucrats.
> > > __/   |http://www.hjp.at/|    -- Charlton Wilbur in clpm- Hide quoted text -
>
> > > - Show quoted text -
>
> > How about SFTP. It seems prity easy to write a script in perl.- Hide quoted text -
>
> > - Show quoted text -
>
> Also, how can I use SFTP on a windows machine?

I have wrote a small script using Net::SFTP::Foreign. I keep getting
the error "invalid option(s) 'dontsave' at sftptest1.pl line 24" not
sure what this means, any help?

#!/usr/bin/perl
#!/usr/bin/sftp
####################################

# This program uses SFTP to login to a remote server. This

# remote server is used to store all the files; UAV GPS,

# Waypoint Verify, and ASOS and Satellite Placefiles. This

# specific test program is used to get the ASOS placefile and

# the Satellite image off of the Mistral Server so that they can be
used.

#

####################################

use strict;

use Net::SFTP::Foreign::Compat;

#login and setup connection

my $host = 'mistral.unl.edu';

my $sftp = Net::SFTP::Foreign::Compat->new($host, user=>'jlahowet');

#change directories (local, remote)

my $local = '/home/deadpickle/Desktop/UAV';


my $remote = '/home/jlahowet/UAV';


$sftp->do_opendir($remote);
$sftp->ls($remote);

#the for loop is used in order to repeat the transfer process


	#get ASOS placefile and Satellite png


	my $sat = 'vis_sat_co.png';

	$sftp->get($sat);



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

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.  

NOTE: due to the current flood of worm email banging on ruby, the smtp
server on ruby has been shut off until further notice. 

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 V11 Issue 245
**************************************


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