[22723] in Perl-Users-Digest

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

Perl-Users Digest, Issue: 4944 Volume: 10

daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Tue May 6 09:51:34 2003

Date: Tue, 6 May 2003 06:05:08 -0700 (PDT)
From: Perl-Users Digest <Perl-Users-Request@ruby.OCE.ORST.EDU>
To: Perl-Users@ruby.OCE.ORST.EDU (Perl-Users Digest)

Perl-Users Digest           Tue, 6 May 2003     Volume: 10 Number: 4944

Today's topics:
    Re: Can't write a LOG file, please help (Sara)
    Re: Checking administrator rights <simon.andrews@bbsrc.ac.uk>
    Re: Checking administrator rights <argonhigh@hotmail.com>
    Re: creating class hierarchies with h2xs (Anno Siegel)
        Design Opinions - Dealing with Constants <kevin.vaughn@ttu.edu>
    Re: escape sequencing problem in Perl <REMOVEsdnCAPS@comcast.net>
        Forcing an rvalue context on a scalar expression <nobull@mail.com>
    Re: Forcing an rvalue context on a scalar expression (Anno Siegel)
    Re: Help: Create Hash On The Fly? <simon.oliver@nospam.umist.ac.uk>
    Re: how to disable Lingua::EN::NameParse print to stdou (Anno Siegel)
        How to fork and PID - revisited <anthony@no_spam.movielink.net.au>
    Re: How to fork and PID - revisited <noreply@gunnar.cc>
    Re: How to fork and PID - revisited <john.thetenant-s@moving-picture.com>
    Re: Including files in Perl <ubl@schaffhausen.de>
    Re: Including files in Perl <temp1_NO_SPAM_@williamc.com>
        Length of line (Tyro)
    Re: Length of line <simon.oliver@nospam.umist.ac.uk>
    Re: Length of line <josef.moellers@fujitsu-siemens.com>
    Re: Length of line (Tad McClellan)
    Re: Length of line <no@spam.for.me.invalid>
        Newbie question Perl Print function using files (Reps)
    Re: Newbie question Perl Print function using files <kasp@epatra.com>
    Re: Newbie question Perl Print function using files <no@spam.for.me.invalid>
    Re: Newbie question Perl Print function using files <nobody@dev.null>
    Re: Newbie question Perl Print function using files (Tad McClellan)
    Re: Newbie question Perl Print function using files <thens@nospam.com>
    Re: perl compiler for win32 platform? <a@b.c>
    Re: shipping perl <nobody@dev.null>
    Re: writing in a new file <bart.lateur@pandora.be>
    Re: XML::DOM parsing error <mirod@xmltwig.com>
        Digest Administrivia (Last modified: 6 Apr 01) (Perl-Users-Digest Admin)

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

Date: 6 May 2003 05:40:01 -0700
From: genericax@hotmail.com (Sara)
Subject: Re: Can't write a LOG file, please help
Message-Id: <776e0325.0305060440.c7533a1@posting.google.com>

gino_vives@yahoo.com (Gino Vives) wrote in message news:<61f4ab48.0305052001.52441ab3@posting.google.com>...
> I wrote a little programe in perl and I haven't be able to write a log
> file, first I use the shell comand: "programe >> logfile" and using
> lines like:
> print "Some text over here";
> 
> As it didn't work I chage the print lines to: (befor I wrote "open
> (LOG ...);")
> print LOG "Some text over here";
> 
> Neither of theses solutions wrote into a file, but the first one (if I
> just esecute "programe") does write in the screen (STDOUT???)
> 
> HELPPPPPPPPPPPPPP!!!! (I feel like a beatle, lmao)
> 
> Here is the script: (The comments are in spanish ;)  )
> 
> 
> 
A few comments..

> 
> 
> #! /usr/local/bin/perl

# olvido' -w!? #! /usr/local/bin/perl -w 

> 
> #ESTA UTILIDAD FUE DISEÑADA Y PROGRAMADA POR JOSE MIGUEL VIVES
> #DUDAS, COMENTARIOS O COOPERACIONES A: jvives@ing.uchile.cl
> 
> while ("1") {
# while (1) es mejor, que ventaja es "1"?

> open (LOG , ">> ../logfile");

# tal vez...
 die "This file wont open,\n$!" unless open LOG, ">>../logfile";


> #Vemos la fecha:
> 
> @fecha = `date`;
# no debe usar `date`. Mira localtime() en vez de esa. como

  @d = localtime();

> 
> $i=0;
# recuerde "my" !!

> 
> while (<@fecha>) {

# no se que es <@fecha>. Es mejor:
  for (@fecha)
   {blah blah}

# de verdad, seria mejor usar "regular expressions" en vez de ese. Seria mas 
# corta y facil. No debe usar "while" y "$i", use "for (@arrray)"..
 
> 
> 	if (/(.*)$/) {
# que es /(.*)$/ ? cualquier scalar es verdad? Que penso'? quiere
#  /./ ?



> 		if ($i == 2) {
> 			$dia = $1;
> 
> 		}
> 	}
> 
> $i++;
> 
> }
> 
> #Ahora vemos cual es el último día del mes
> 
> @calendario = `cal`;
> $ultimo = 0;
> $numeros = 0;
> 
> while (<@calendario>) {
> 	if ($numeros) {
> 		$ultimo ++;
> 	}
> 		
> 	if (/(.*)/) {
> 		if ($1 eq "S") 

# cuando se tiene un constante como S, es mejor usar ' como 'S'..
{
> 			$numeros = 1;
> 		}
> 	}
> }
> $
> 
> 


Buena Suerte!
-Gx


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

Date: Tue, 06 May 2003 10:28:52 +0100
From: Simon Andrews <simon.andrews@bbsrc.ac.uk>
Subject: Re: Checking administrator rights
Message-Id: <3EB78054.3010909@bbsrc.ac.uk>


Gert Vanderstukken wrote:
> Hello all,
> 
> I'm looking for a way to check if the script is ran under an
> administrative account, but I cannot seem to find it.

 > I'm using perl on a Windows NT system.

I suppose this depends on how you define an administrative account.  If 
you can determine this from the username then getlogin() will return the 
current user.  For a more generic solution you're probably going to have 
to look into the Win32 mailing lists.

Simon.



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

Date: Tue, 6 May 2003 00:17:15 -0400
From: "James" <argonhigh@hotmail.com>
Subject: Re: Checking administrator rights
Message-Id: <G3Ota.3432$VJ.317819@news20.bellglobal.com>

> I'm sorry, but I cannot find the parameter to use. I'm using perl on a
> Windows NT system.

This will work


###
use Win32::API;
$isadmin = new Win32::API('advpack.dll', 'IsNTAdmin', 'NN', 'N');
$status=$isadmin->Call(0,0);
if($status != 0) { print "You are an administrator."; }
else { print "You are not an administrator."; }
###
#http://www.mentalis.org/apilist/IsNTAdmin.shtml




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

Date: 6 May 2003 10:07:33 GMT
From: anno4000@lublin.zrz.tu-berlin.de (Anno Siegel)
Subject: Re: creating class hierarchies with h2xs
Message-Id: <b981h5$1bt$1@mamenchi.zrz.TU-Berlin.DE>

Jason Parker-Burlingham  <jasonp@uq.net.au> wrote in comp.lang.perl.misc:
> anno4000@lublin.zrz.tu-berlin.de (Anno Siegel) writes:
> 
> > Quite.  Try ExtUtils::ModuleMaker from CPAN, which allows to create
> > the structure for more than on module in one go.
> 
> That's what I hit on after checking with Perlmonks.org; I've used it
> and it appears to work very well (although using Test::More increases
> the number of modules I'll have to install on the client's host).
> 
> > You still have to have your modules planned out from the start.  If
> > you later think you need another module in your project and run
> > ModuleMaker again, it will overwrite your work up to then, no
> > questions asked.
> 
> My one try at adding a module afterward by hand seemed to indicate
> that I could just create directories and add .pm files as necessary.
> Do I need to update MANIFEST on my own or is it somehow done for me?

"make manifest" should be independent of the modules you named to
ModuleMaker.  It works pretty much on the fly.  But then, if you're
going to add modules manually, you might as well start with a single
h2xs-created module and add everything by hand (well almost).

I am using a module that I derived from ModuleMaker.  It calls ModuleMaker
in a directory outside the current build tree and then transfers those
files that don't already exist.

Anno


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

Date: Tue, 6 May 2003 08:38:27 -0500
From: "Kevin Vaughn" <kevin.vaughn@ttu.edu>
Subject: Design Opinions - Dealing with Constants
Message-Id: <vbfemoj1e9hba1@corp.supernews.com>

I've created a large number of scripts that reference a single file
containing all of my constants.  I named the file environment.pl.  The file
mainly contains paths.  I include environment.pl using a "required"
statement.

Is this good or bad design?  I'm particularly interested in the downsides.

Now a specific question - How do I get perl to stop giving me the error
"Global symbol $constant_from_environment requires explicit package name at
$line_number" when I have strict turned on?

I'm trying to get my head around the lexical vs. package scope thing, but
it's not coming easy for some reason.  Do I have to go through creating a
package, or can I use "our"?

-Kevin




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

Date: Tue, 06 May 2003 04:42:38 -0500
From: "Eric J. Roode" <REMOVEsdnCAPS@comcast.net>
Subject: Re: escape sequencing problem in Perl
Message-Id: <Xns93733A118DF6Asdn.comcast@216.166.71.239>

-----BEGIN xxx SIGNED MESSAGE-----
Hash: SHA1

prakashpms@hotmail.com (Prakash) wrote in
news:afc6e663.0305052143.2946247f@posting.google.com: 

> "Kasp" <kasp@epatra.com> wrote in message
> news:<b966db$afq$1@newsreader.mailgate.org>... 
>> Yes, there is more than one way of doing it.
>> 
>> May I point the OP to quotemeta function which I find
particularly
>> useful but less talked about.
> 
> 
> The problem I am facing is that one of the programs returns
something
> like this string with lots of "\" characters. I want to store them
in
> a variable and process it as such. But, when I store and use the
> variable, I get only half the number of "\"es what the program
> returned. I do not want perl to escape sequence the variable.

Perl does not do that.  You are either doing something strange and
overly complex (like eval) or you are misinterpreting what's going
on.

Can you post a short bit of code that shows this
disappearing-backslash problem?

- -- 
Eric
print scalar reverse sort qw p ekca lre reh 
ts uJ p, $/.r, map $_.$", qw e p h tona e;
-----BEGIN xxx SIGNATURE-----
Version: GnuPG v1.2.1 (MingW32) - WinPT 0.5.13

iD8DBQE+t4OAY96i4h5M0egRAtJ7AJ0V6V8N7cBQ3nOgsj26cS3u1HrOgACg3JPq
AIbtgJ2odRIQ6uLV/4O1Nb8=
=SLP4
-----END PGP SIGNATURE-----


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

Date: 06 May 2003 13:42:14 +0100
From: Brian McCauley <nobull@mail.com>
Subject: Forcing an rvalue context on a scalar expression
Message-Id: <u98ytk6yc9.fsf@wcl-l.bham.ac.uk>

What is the simplest way to force an rvalue context on a scalar
expression?

For example, consider:

my @q;
foo($q[-1]);

This generates "Modification of non-creatable array value attempted,
subscript -1" because it's trying to evaluate $q[-1] as an lvalue but
I just wanted foo's $_[0]=undef.

I can easily, but not very elegantly, fix this by saying:

my $last_q = $q[-1];
foo($last_q);

Or even...

foo(my $last_q = $q[-1]);

Or, without a varaiable, but more perversely...

foo(&{sub { $q[-1] }});

Anyone got any less ugly solutions?

-- 
     \\   ( )
  .  _\\__[oo
 .__/  \\ /\@
 .  l___\\
  # ll  l\\
 ###LL  LL\\


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

Date: 6 May 2003 13:32:12 GMT
From: anno4000@lublin.zrz.tu-berlin.de (Anno Siegel)
Subject: Re: Forcing an rvalue context on a scalar expression
Message-Id: <b98dgs$baj$1@mamenchi.zrz.TU-Berlin.DE>

Brian McCauley  <nobull@mail.com> wrote in comp.lang.perl.misc:
> What is the simplest way to force an rvalue context on a scalar
> expression?
> 
> For example, consider:
> 
> my @q;
> foo($q[-1]);
> 
> This generates "Modification of non-creatable array value attempted,
> subscript -1" because it's trying to evaluate $q[-1] as an lvalue but

Isn't that a bug?  I mean, you're not assigning anything, are you?

> I just wanted foo's $_[0]=undef.
> 
> I can easily, but not very elegantly, fix this by saying:
> 
> my $last_q = $q[-1];
> foo($last_q);
> 
> Or even...
> 
> foo(my $last_q = $q[-1]);
> 
> Or, without a varaiable, but more perversely...
> 
> foo(&{sub { $q[-1] }});

Along the same line as sub {...}:

    foo( do { $q[-1] } );

and, found coincidentally, and not quite understood:

    do( scalar $q[ -1]);

I still think it's a bug.  Why should scalar vs. list context make
a difference?

Anno


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

Date: Tue, 06 May 2003 08:16:58 +0100
From: Simon Oliver <simon.oliver@nospam.umist.ac.uk>
Subject: Re: Help: Create Hash On The Fly?
Message-Id: <3EB7616A.8090603@nospam.umist.ac.uk>

entropy123 wrote:
> Hey all,
> 
> One thing I can't figure out is how to create a hash on the fly:

> Lets say the following are my relationships: A0 & B1 =2, A0 & C2 = 1
> A0 & A3 = 3 so:
> 
> hashA0 = (B1,2,A0,1,A3,3)
> hashB1 = (A0,2)
> hashC2 = (A0,1)
> hashA3 = (A0,3)
> 
> When I start to read each file I have no idea how many hashes I'll
> require and pretty much need to create them on the fly. How do I pull
> this off? I'd really like to have the element and sequential number as
> part of the hash name.
> 
You want a hash of hashes:

my %hoh = ();

$hoh{A0} = {B1=>2, A0=>1, A3=>3};

To get the values out:

my $val = $hoh{A0}{B1};

-- 
   Simon Oliver



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

Date: 6 May 2003 10:13:58 GMT
From: anno4000@lublin.zrz.tu-berlin.de (Anno Siegel)
Subject: Re: how to disable Lingua::EN::NameParse print to stdout?
Message-Id: <b981t6$1bt$2@mamenchi.zrz.TU-Berlin.DE>

Bing Du Test  <bing-du@tamu.edu> wrote in comp.lang.perl.misc:

Please don't top-post.  Put your reply in context.

> This is the first four lines of the script.
> 
> ==========
> #!/usr/local/bin/perl
> 
> use locale;
> use Lingua::EN::NameParse qw(clean case_surname);
> <snip...>
> ==========
> 
> Code snippet of Lingua::EN::NameParse:
> 
> ======
> print STDERR "Assembling with: <$input_string>\n";
  ^^^^^
That is in v 1.18 of Lingua::EN::NameParse?  It certainly doesn't
belong there, and my version doesn't have it.  Re-install the
module from CPAN.

[snip]

Anno


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

Date: Tue, 06 May 2003 20:10:24 +1000
From: "Tony" <anthony@no_spam.movielink.net.au>
Subject: How to fork and PID - revisited
Message-Id: <pan.2003.05.06.10.10.23.926651@no_spam.movielink.net.au>



Hi Guys,

Beginner question about implementing fork:
(Sorry I am asking again - a couple of people
have given suggestions in the past but the
suggestions failed - surely because my
implementation was flawed, not the posters)


My program snippet:

 ...some preceeding code...

my $process_file_pid = 0;
my $file = "/path/to/file";

START: open (FILE, $file) or die "Could not open: $file\n";
  foreach my $schedule(<FILE>)
    {
    my $local_time_day = day_time();        # code not shown for this
    my $time_day = (extracted from $file);  # code not shown for this
    my $data = (extracted from $file);      # code not shown for this
    if ("$local_time_day eq $time_day")     # Compare for a match...
        {
        process_data($data);
        }
    }

goto START;


The above continuesly scans $file for a day/time match and passes
a list of files to the sub "process_data" when a match happens.

The sub "process_data" then sends the list of files, one a a time,
to another sub "process_file".  This sub will process the file,
return for the next file and so on until all have been processed.


All runs fine before adding any "fork" functionality.

I tried the following:

   if ("$local_time_day eq $time_day")     # Compare for a match...
        {
        if (fork() == 0)
          {
          my $child_pid = $$;      # Get child PID
          close SCHEDULE;          # Close previously opened file handle
          process_data($data);     # Send data to be processesed by sub
          exit;                    # Exit child if processing completed
          }
        }
    }

That does work (Start a new process) but various docs talk about signals,
kids, $$ for PID etc. which has confused me.

The "process_file" program is something like:

sub process_file
   {
   ...
   my $external = "/some/path/program";
   my $file = $_[1];
   my $params = "abc";
   system "$external $params $file";
   }


It would seem that the external file processor should
be started something like:

sub process_file
   {
   ...
   if (fork() == 0)
     {
     $pocess_file_pid = $$;  # Get players PID before EXEC
     exec "$external $params $file"; or die "Could not exec $!\n";
     }
   }

I see a small problem here - this snippet will return as soon as
it has strated the external program, resulting in an attempt to
process the next file - this will "blow up" as the current file
is still being processed.  I somehow need to have the "process_data"
sub check for the process running and when it is finished, send
the next file.

Could i use "waitpid" for that by checking the  $process_pid ?

What is the right way to store the pid's and where?  I have defined
a $process_file_id at the beginning and then substituting its
value with $$ after fork.

I want to be able to store the $process_file_pid and $child_pid somewhere
so that I can kill both processes if a new event is trigered by my
main loop at the beginning.  This will enable me to run a new
set of files.

It is a bit of a moutfull, am I on the right path?

Tony

 
    


-- 
--------------------------------------------------------------
To reply dir directly send to: anthony AT movielink DOT net DOT au
Replace AT and DOT with @ and . and mail will get through.




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

Date: Tue, 06 May 2003 13:37:13 +0200
From: Gunnar Hjalmarsson <noreply@gunnar.cc>
Subject: Re: How to fork and PID - revisited
Message-Id: <b9871q$gdi0v$1@ID-184292.news.dfncis.de>

Tony wrote:
> Beginner question about implementing fork:

I'm too much of a beginner to be able to answer your questions, but I 
have successfully forked child processes by help of the CPAN module 
Parallel::ForkManager.

/ Gunnar

-- 
Gunnar Hjalmarsson
Email: http://www.gunnar.cc/cgi-bin/contact.pl



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

Date: Tue, 6 May 2003 13:34:09 +0100
From: John Strauss <john.thetenant-s@moving-picture.com>
Subject: Re: How to fork and PID - revisited
Message-Id: <20030506133409.04f4ee29.john.thetenant-s@moving-picture.com>

On Tue, 06 May 2003 20:10:24 +1000
"Tony" <anthony@no_spam.movielink.net.au> wrote:
>
> 
> 
> Hi Guys,
> 
> Beginner question about implementing fork:
> (Sorry I am asking again - a couple of people
> have given suggestions in the past but the
> suggestions failed - surely because my
> implementation was flawed, not the posters)
> 
> 
> My program snippet:
> 
> ...some preceeding code...
> 
> my $process_file_pid = 0;
> my $file = "/path/to/file";
> 
> START: open (FILE, $file) or die "Could not open: $file\n";
>   foreach my $schedule(<FILE>)
>     {
>     my $local_time_day = day_time();        # code not shown for this
>     my $time_day = (extracted from $file);  # code not shown for this
>     my $data = (extracted from $file);      # code not shown for this
>     if ("$local_time_day eq $time_day")     # Compare for a match...

your "compare for a match" is broken.  take out the double quotes.  unless they are a part of your scheme for presenting psuedocode (?)


>         {
>         process_data($data);
>         }
>     }
> 
> goto START;
> 
> 
> The above continuesly scans $file for a day/time match and passes
> a list of files to the sub "process_data" when a match happens.

you might want to consider a "while (1)" loop rather than a goto.  it may not amount to much, but i think it's more conventional.  you may also find that you want to add a "sleep (1)" to keep your program from hogging alot of cpu.


> 
> The sub "process_data" then sends the list of files, one a a time,
> to another sub "process_file".  This sub will process the file,
> return for the next file and so on until all have been processed.
> 
> 
> All runs fine before adding any "fork" functionality.
> 
> I tried the following:
> 
>    if ("$local_time_day eq $time_day")     # Compare for a match...
>         {
>         if (fork() == 0)
>           {
>           my $child_pid = $$;      # Get child PID
>           close SCHEDULE;          # Close previously opened file handle
>           process_data($data);     # Send data to be processesed by sub
>           exit;                    # Exit child if processing completed
>           }
>         }
>     }
> 
> That does work (Start a new process) but various docs talk about signals,
> kids, $$ for PID etc. which has confused me.

you really need to understand fork to use it well.


> 
> The "process_file" program is something like:
> 
> sub process_file
>    {
>    ...
>    my $external = "/some/path/program";
>    my $file = $_[1];

is $_[1] defined?  i thought you were calling "process_file($data)"


>    my $params = "abc";
>    system "$external $params $file";
>    }
> 
> 
> It would seem that the external file processor should
> be started something like:
> 
> sub process_file
>    {
>    ...
>    if (fork() == 0)
>      {
>      $pocess_file_pid = $$;  # Get players PID before EXEC
>      exec "$external $params $file"; or die "Could not exec $!\n";
>      }
>    }
> 
> I see a small problem here - this snippet will return as soon as
> it has strated the external program, resulting in an attempt to
> process the next file - this will "blow up" as the current file
> is still being processed.  I somehow need to have the "process_data"
> sub check for the process running and when it is finished, send
> the next file.
> 
> Could i use "waitpid" for that by checking the  $process_pid ?
> 
> What is the right way to store the pid's and where?  I have defined
> a $process_file_id at the beginning and then substituting its
> value with $$ after fork.
> 
> I want to be able to store the $process_file_pid and $child_pid somewhere
> so that I can kill both processes if a new event is trigered by my
> main loop at the beginning.  This will enable me to run a new
> set of files.
> 
> It is a bit of a moutfull, am I on the right path?
> 
> Tony
> 
>  
from what i can understand of your problem, i wouldn't use exec(), nor an external program.  just use fork, which returns the child's pid.  store the child's pid in a variable in your parent process.  use a signal handler for CHLD to do waitpid on the child process, and clear the child pid variable.  if your main loop gets a new match, and the child pid variable has a pid in it, kill the child before the process_data() routine. (and don't forget to throw out the bath water with the baby).





~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
drop the .thetenant to get me via mail


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

Date: Tue, 06 May 2003 10:25:06 +0200
From: Malte Ubl <ubl@schaffhausen.de>
Subject: Re: Including files in Perl
Message-Id: <b97ulv$nep$1@news.dtag.de>

James E Keenan wrote:

>         $SERVER = 'foo';
> 
> Hence, no 'our' in the included file ... only in the script.

Why not? It makes the required file strict safe.

malte.exe



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

Date: Tue, 06 May 2003 11:43:42 GMT
From: PropART <temp1_NO_SPAM_@williamc.com>
Subject: Re: Including files in Perl
Message-Id: <3EB79F63.A20F1BA6@williamc.com>


> > I was hoping that there was some way I didn't know about e.g. making the
> > included file a module, but I don't know squat about object oriented
> > Perl...



James E Keenan wrote:

> Two points:
> 1.  Perl has 2 types of modules:  (a) "traditional", non-object-oriented
> modules which export their symbols (generally, their subroutines) into the
> main package; and (b) object-oriented modules which do not export any
> symbols but which provide methods.  So knowing little about OOP does not
> disqualify you from considering a non-OOP module.  See 'perldoc perlmod' ...
> go down to the section on Perl Modules.
> 2.  That being said, here you're only looking to import the name of a
> scalar, not a subroutine, into your main package.  For this, you don't need
> modules; a separate text file with the scalar (or array or hash) will
> suffice.  Predeclare the variable in the main package with 'our'; then
> import with 'require' (or, under some circumstances, 'do') and you will have
> no problem, with little fuss.


So, if I'm understanding everything that's being said in this thread
correctly, the situation is this:

if I want to put a bunch of scalar variable in an include file AND use
strict in the including files, I'll need to declare the variables with
our in the including file. Which also implies that if I change the
include file I'll need to change the declaration in all of the including
files. 

However, your suggestion of putting the values into a hash could work
around the problem at the expense of a little extra code to get the
value out of the hash. Thanks for the help. 

--wmc.


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

Date: 6 May 2003 04:09:57 -0700
From: alonsnizer@walla.co.il (Tyro)
Subject: Length of line
Message-Id: <2a24fe91.0305060309.174680dd@posting.google.com>

Hi all!

I'm a new in Perl so sorry if it trivial.

How can I determine the length of line I get from file?
length($_) isn't good enough - it counts any white space (\r\t\n\f) as
1.
But what if my tab (\t) actually takes four (4) spaces.

The purpose of this is to check during compilation that my source
files lines not longer than 80 (some of platforms can't stand it
longer).

Thanks for advice,

Alon


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

Date: Tue, 06 May 2003 12:31:50 +0100
From: Simon Oliver <simon.oliver@nospam.umist.ac.uk>
Subject: Re: Length of line
Message-Id: <3EB79D26.3040507@nospam.umist.ac.uk>

Tyro wrote:
> Hi all!
> 
> I'm a new in Perl so sorry if it trivial.
> 
> How can I determine the length of line I get from file?
> length($_) isn't good enough - it counts any white space (\r\t\n\f) as
> 1.
> But what if my tab (\t) actually takes four (4) spaces.

Trailing non word characters could be removed using s/\W*$// although 
chomp() is probably best here.;

A tab represents no specific length - in Word it is half an inch by 
default and in notepad it is eight characters.  Many programmers set tabs 
to two or four characters.

You have to decide how many charachters a tab is equivalent to.  You could 
use tr/\t/\t/ to count the number of tabs and add $tabs*($size-1) to 
length($_).  Or simply s/\t/        /g prior to length($_);


-- 
   Simon Oliver





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

Date: Tue, 06 May 2003 14:14:55 +0200
From: Josef =?iso-8859-1?Q?M=F6llers?= <josef.moellers@fujitsu-siemens.com>
Subject: Re: Length of line
Message-Id: <3EB7A73F.5A6C83EB@fujitsu-siemens.com>

Simon Oliver wrote:
> =

> Tyro wrote:
> > Hi all!
> >
> > I'm a new in Perl so sorry if it trivial.
> >
> > How can I determine the length of line I get from file?
> > length($_) isn't good enough - it counts any white space (\r\t\n\f) a=
s
> > 1.
> > But what if my tab (\t) actually takes four (4) spaces.
> =

> Trailing non word characters could be removed using s/\W*$// although
> chomp() is probably best here.;
> =

> A tab represents no specific length - in Word it is half an inch by
> default and in notepad it is eight characters.  Many programmers set ta=
bs
> to two or four characters.
> =

> You have to decide how many charachters a tab is equivalent to.  You co=
uld
> use tr/\t/\t/ to count the number of tabs and add $tabs*($size-1) to
> length($_).  Or simply s/\t/        /g prior to length($_);

This will definitely not work as it does not take the varying amount of
white space into account.

The following is tested:
Depending on the absolute position wrt the beginning of the line, a tab
will expand to 1 to 8 blanks. A small experiment yields that a tab in
position (x) will expand to (8 - x mod 8) blanks, so the following piece
of code should work =


while (($pos =3D index($line, "\t")) !=3D -1) {
    substr($line, $pos, 1, substr(' ' x 8, 0, (8 - $pos % 8)));
}

Maybe there's a module to do this ...

-- =

Josef M=F6llers (Pinguinpfleger bei FSC)
	If failure had no penalty success would not be a prize
						-- T.  Pratchett


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

Date: Tue, 6 May 2003 07:32:23 -0500
From: tadmc@augustmail.com (Tad McClellan)
Subject: Re: Length of line
Message-Id: <slrnbbfaqn.3ej.tadmc@magna.augustmail.com>

Tyro <alonsnizer@walla.co.il> wrote:

> How can I determine the length of line I get from file?
> length($_) isn't good enough - it counts any white space (\r\t\n\f) as
> 1.


length() counts the number of _characters_, ie. the length of a _string_.


> But what if my tab (\t) actually takes four (4) spaces.


That is a function of your output device. Tabs can expand to
4 spaces each on one terminal and 8 spaces each on another terminal.


> The purpose of this is to check during compilation that my source
> files lines 


You do not what to count characters in a string, you want to
count characters in a _line_.


> not longer than 80 (some of platforms can't stand it
> longer).


The you will need to hard-code the width of tabs to one particular 
value, then use length().

   perldoc -q tabs

      How do I expand tabs in a string?


A better solution would be to use a module to wrap your text for you,
such as Text::Wrap.


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


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

Date: Tue, 06 May 2003 13:24:10 GMT
From: "Nils Petter Vaskinn" <no@spam.for.me.invalid>
Subject: Re: Length of line
Message-Id: <pan.2003.05.06.13.24.09.875442@spam.for.me.invalid>

On Tue, 06 May 2003 04:09:57 -0700, Tyro wrote:

> Hi all!
[snip counting characters]
> The purpose of this is to check during compilation that my source
> files lines not longer than 80 (some of platforms can't stand it
> longer).

I think you have got the answer to your question how to count with the
with of a tab character. But I suspect you're trying to solve the wrong
problem.

If your compiler chokes on 80 characters it's likly that a tab character
counts as one character. Try to create a line with less than 80 characters
(tabs counting as one) but a length more than 80 when tabs are expanded.
If that compiles on all platforms you can use length($_) without worry.

regards
NPV


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

Date: 6 May 2003 05:23:05 -0700
From: repsg@btclick.com (Reps)
Subject: Newbie question Perl Print function using files
Message-Id: <cf9445fa.0305060423.2bbf2a16@posting.google.com>

Hi there,
I have a small problem.  I aiming to open a file and write to the file on one line>

I have my variables such as:

$firstname , $lastname , $gender etc.

I use the print function

open(CSVFILE, "contacts.csv");
print CSVFILE "${firstname} , ${lastname} , ${gender}"; 
close(CSVFILE);

the output i WANT from contact.csv is:

fisrtname,lastname,gender

instead i get this when i open contact.csv

firstname
,lastname
,gender

how do fix this ??

thanks in-advance!

reps


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

Date: Tue, 6 May 2003 18:20:46 +0530
From: "Kasp" <kasp@epatra.com>
Subject: Re: Newbie question Perl Print function using files
Message-Id: <b98b65$cre$1@newsreader.mailgate.org>

> print CSVFILE "${firstname} , ${lastname} , ${gender}";

try instead
    print CSVFILE "$firstname , $lastname , $gender";

--
"Accept that some days you are the pigeon and some days the statue."
"A pat on the back is only a few inches from a kick in the butt." - Dilbert.




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

Date: Tue, 06 May 2003 13:17:44 GMT
From: "Nils Petter Vaskinn" <no@spam.for.me.invalid>
Subject: Re: Newbie question Perl Print function using files
Message-Id: <pan.2003.05.06.13.17.44.301825@spam.for.me.invalid>

On Tue, 06 May 2003 05:23:05 -0700, Reps wrote:

> Hi there,
[snip]
> how do fix this ??


Your firstname lastname and possibly gender contain newlines at the end.

chomp $firstname;
chomp $lastname;
chomp $gender;

HTH
Nils P


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

Date: Tue, 06 May 2003 13:18:06 GMT
From: Andras Malatinszky <nobody@dev.null>
Subject: Re: Newbie question Perl Print function using files
Message-Id: <3EB7B5C1.605@dev.null>

Reps wrote:
[...]

> I have my variables such as:
> 
> $firstname , $lastname , $gender etc.
> 
> I use the print function
[...]
> print CSVFILE "${firstname} , ${lastname} , ${gender}"; 


Firs of all, there is no need for the curly brackets. You can just say

print CSVFILE "$firstname,$lastname,$gender\n";

(You will want a "\n" at the end because you want the next set of 
$firstname/$lastname/$gender to be on a new line.)

[...]


> 
> the output i WANT [...] is:
> 
> fisrtname,lastname,gender
> 
> instead i get this 


[...]
> 
> firstname
> ,lastname
> ,gender
> 


You probably have newline characters at the end of the strings stored in 
your variables. Use chomp to get rid of them before printing:

chomp($firstname, $lastname, $gender);




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

Date: Tue, 6 May 2003 08:23:01 -0500
From: tadmc@augustmail.com (Tad McClellan)
Subject: Re: Newbie question Perl Print function using files
Message-Id: <slrnbbfdpl.3ic.tadmc@magna.augustmail.com>

Reps <repsg@btclick.com> wrote:

> I have my variables such as:
> 
> $firstname , $lastname , $gender etc.


Do the values of those variables in with a newline perhaps?

Did you read them in from a file?


> I use the print function
> 
> open(CSVFILE, "contacts.csv");
> print CSVFILE "${firstname} , ${lastname} , ${gender}"; 


Those curly braces are not needed, they get in the way of
reading/understanding the code.


> close(CSVFILE);
> 
> the output i WANT from contact.csv is:
> 
> fisrtname,lastname,gender


Surely you meant this instead?

   firstname , lastname , gender


> instead i get this when i open contact.csv
> 
> firstname
> ,lastname
> ,gender
> 
> how do fix this ??


chomp() the values before printing them:

    chomp for $firstname, $lastname, $gender;

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


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

Date: Tue, 6 May 2003 18:56:36 +0530
From: Thens <thens@nospam.com>
Subject: Re: Newbie question Perl Print function using files
Message-Id: <20030506185636.6d1a0cc4.thens@nospam.com>

On 6 May 2003 05:23:05 -0700
repsg@btclick.com (Reps) wrote:

: 
: $firstname , $lastname , $gender etc.
: 
: I use the print function
: 
: open(CSVFILE, "contacts.csv");
: print CSVFILE "${firstname} , ${lastname} , ${gender}"; 
: close(CSVFILE);

  With this code you would not have got  anything in contacts.csv. You
  want to write  to the file contacts.csv but  you did not ask perl to
  open it for writing. You would have caught  this had you checked for
  the   success of the    open. You should   alwyas  check if the open
  succeeded or not .
 
  open(CSVFILE, ">contacts.csv") or die "Cannot open file for writing : $!";
  print CSVFILE "$firstname, $lastname, $gender";
  close CSVFILE;

   This wont  solve your problem  with the broken  lines in  the output
  file. The reason for that is not clear from the bit of code that you
  have  sent. Where do you  assign the value  to variables $firstname,
  $lastnamem $gender  ?  If  you are accepting   the  value from  user
  probably you should chomp before you assign the value.

  my $firstname = <STDIN>; 
  chomp $firstname;


  for more information read

   perldoc -f open
   perldoc -f chomp


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

Date: Tue, 06 May 2003 14:01:41 +0200
From: ZZT <a@b.c>
Subject: Re: perl compiler for win32 platform?
Message-Id: <b98875$hin$1@news1.wdf.sap-ag.de>

Hello Simon,

thanks first for your answer :) and sorry for the long delay.

> All you should need to do is to download the tar.gz from the address I 
> gave you above, and unzip it to a temp directory (making sure you keep 
> the folder organisation in the tar file), then open a command shell, 
> move to that directory and type
> 
> perl Makefile.PL
ran fine as far is I saw:
*** ExtUtils::AutoInstall version 0.50
*** Checking for dependencies...
[Core Features]
- File::Temp       ...loaded. (0.12)
- Compress::Zlib   ...loaded. (1.16 >= 1.14)
- Archive::Zip     ...loaded. (1.05 >= 1)
- Module::ScanDeps ...loaded. (0.19 >= 0.19)
*** ExtUtils::AutoInstall configuration finished.
Note (probably harmless): No library found for 'oldnames.lib'
Note (probably harmless): No library found for 'kernel32.lib'
Note (probably harmless): No library found for 'user32.lib'
Note (probably harmless): No library found for 'gdi32.lib'
Note (probably harmless): No library found for 'winspool.lib'
Note (probably harmless): No library found for 'comdlg32.lib'
Note (probably harmless): No library found for 'advapi32.lib'
Note (probably harmless): No library found for 'shell32.lib'
Note (probably harmless): No library found for 'ole32.lib'
Note (probably harmless): No library found for 'oleaut32.lib'
Note (probably harmless): No library found for 'netapi32.lib'
Note (probably harmless): No library found for 'uuid.lib'
Note (probably harmless): No library found for 'wsock32.lib'
Note (probably harmless): No library found for 'mpr.lib'
Note (probably harmless): No library found for 'winmm.lib'
Note (probably harmless): No library found for 'version.lib'
Note (probably harmless): No library found for 'odbc32.lib'
Note (probably harmless): No library found for 'odbccp32.lib'
Note (probably harmless): No library found for 'msvcrt.lib'
Writing Makefile for the par.exe program


> ..then sit back whilst it checks everything it needs.  If you've not run 
> it before then it will probably download nmake.exe for you.  Once this 
> has completed you run (in the same directory)...
> nmake
here I got:
Microsoft (R) Program Maintenance Utility   Version 1.50
Copyright (c) Microsoft Corp 1988-94. All rights reserved.

         link main.obj -release   -nologo -nodefaultlib -release 
-libpath:"C:/pr
ogram files/tools/perl\lib\CORE"  -machine:x86  "C:\program 
files\tools\perl\lib
\CORE\perl56.lib" -out:.\par.exe
main.obj : error LNK2001: unresolved external symbol 
__imp__DeleteCriticalSectio
n@4
LINK : error LNK2001: unresolved external symbol _mainCRTStartup
 .\par.exe : fatal error LNK1120: 2 unresolved externals
NMAKE : fatal error U1077: 'C:\WINNT\system32\cmd.exe' : return code '0x460'
Stop.
NMAKE : fatal error U1077: 'C:\WINNT\system32\cmd.exe' : return code '0x2'
Stop.

> nmake test
> 
> nmake install
> 
> ..and that's it, it should all be installed for you.  If this doesn't 
> work then let us know at which stage it fails, and with what error

last 2 steps still open due to error in "nmake" step.
Any hints?

Regards



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

Date: Tue, 06 May 2003 11:51:37 GMT
From: Andras Malatinszky <nobody@dev.null>
Subject: Re: shipping perl
Message-Id: <3EB7A17D.1020207@dev.null>



Prashanth wrote:

> Hi,
> 
> I want to ship perl with our software (my employer's; not mine :) ),
> as our software has a perl script and we don't want to rely on our
> customer to have a Perl installation; but, I don't want to ship entire
> Perl installation. Here are my doubts:
> 
> 1. The perl script in our software, does not have any 'use', 'do EXPR'
> or 'require' constructs. So I don't want to ship any modules. Will
> this be OK?
> 
> 2. The things which we are going to ship are,
>    i) Perl interpreter - perl.
>   ii) Copy of Artistic license.
>  iii) Copy of "Copying".
>  Is this OK? Should I include anything more?
> 
> 3. I would like to ship perl built on Solaris 32 bit platform, for
> Solaris 64 bit platform also. Will this cause any problem?
> 
> It will be very helpful, if you people can clear my doubts.
> 
> Thank you,
> Prashanth.
> 


Take a look at perl2exe (http://www.indigostar.com/perl2exe.htm) to see 
if that helps you.





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

Date: Tue, 06 May 2003 13:44:12 GMT
From: Bart Lateur <bart.lateur@pandora.be>
Subject: Re: writing in a new file
Message-Id: <e0ffbv84j6k56kmolhsuimckgt52v6ham9@4ax.com>

Sam Jesse wrote:

>sorry, I did not explain myself correctly, let me have another go.
>C:/perl perldoc -f print
>Can't open perl script "perldoc": No such file or directory

Just "perldoc". It's actually a perl script wrapped in a .BAT file,
"perldoc.bat". It's right next to the perl executable in the "bin"
directory.

-- 
	Bart.


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

Date: Tue, 06 May 2003 15:28:02 +0200
From: Michel Rodriguez <mirod@xmltwig.com>
Subject: Re: XML::DOM parsing error
Message-Id: <b98d94$dp6$1@news-reader13.wanadoo.fr>

Hi,

Your problem is that you seem to be confusing DOM nodes (like $field in your
code) and strings (like $value). These are not interchangeable. You need to
use $field->toString for the field name, and $doc->createTextNode( $value)
to create a text node that can be inserted in the DOM. See code below.

I would not consider the DOM suitable for this though. Do yourself a favor
and grab XML::LibXML (and always use findnodes instead of the navigation
functions), basically any SAX module, or XML::Twig. 

In this short example, if a comment is inserted in the cimple element, then
$elem->getFirstChild() will not return what you think it will, and you will
get into trouble. Plus the DOM is a real pain to use.

Anyway, now that I have vented my frustration ;--( here is the code:

#!/usr/bin/perl -w
use strict;
use XML::DOM;

my $xp = new XML::DOM::Parser(); 
my $doc = $xp->parse(\*DATA); 

my %self= ( Field_Name => "[the field value]");

foreach my $elem ($doc->getElementsByTagName("cimple")){ 
   my $field=$elem->getFirstChild();     # a node, hopefully the field name  
   my $field_name= $field->toString;     # a string 
   my $value=$self{$field_name};         # a string
   my $text_node=  $doc->createTextNode( $value); # a text node
   $elem->replaceChild($text_node,$field);        
} 

print $doc->toString;

__DATA__
<dc:title> 
   Title 
   <cimple>Field_Name</cimple> 
</dc:title> 

-- 
__
Michel Rodriguez
Perl &amp; XML
http://xmltwig.com


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

Date: 6 Apr 2001 21:33:47 GMT (Last modified)
From: Perl-Users-Request@ruby.oce.orst.edu (Perl-Users-Digest Admin) 
Subject: Digest Administrivia (Last modified: 6 Apr 01)
Message-Id: <null>


Administrivia:

The Perl-Users Digest is a retransmission of the USENET newsgroup
comp.lang.perl.misc.  For subscription or unsubscription requests, send
the single line:

	subscribe perl-users
or:
	unsubscribe perl-users

to almanac@ruby.oce.orst.edu.  

To submit articles to comp.lang.perl.announce, send your article to
clpa@perl.com.

To request back copies (available for a week or so), send your request
to almanac@ruby.oce.orst.edu with the command "send perl-users x.y",
where x is the volume number and y is the issue number.

For other requests pertaining to the digest, send mail to
perl-users-request@ruby.oce.orst.edu. Do not waste your time or mine
sending perl questions to the -request address, I don't have time to
answer them even if I did know the answer.


------------------------------
End of Perl-Users Digest V10 Issue 4944
***************************************


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