Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Locked thread
Triple Tech
Jul 28, 2006

So what, are you quitting to join Homo Explosion?

mister_gosh posted:

If someone CTRL-C's this script, nothing gets put in to C:/example.txt. Is there a way to ensure it closes properly or a better way of doing this?

Edit: thinking about this some more, is there a way to do something like if a user does CTRL-C or if there is an abrupt end or big error, can the program say "on exit, close this file handle?"

Two things. One, it sounds like what you're asking for is to output to a file as soon as possible. That is achieved by the following:

code:
$|++;
I'm fully aware that it looks crazy, but that's the way most Perl programmers write it. It sets the output autoflush variable to true. That means every time something gets sent to a filehandle, it will definitely show up. I don't think a handle needs to be closed to be written to this way, that's what I'm banking on.

The other thing is how to clean up a mess when you've been interrupted. You get around that with a signal handler. I believe the Ctrl-C signal is SIGINT. You override that handler with your code and it will be run every time someone interrupts your program. But that's probably not what you want to do here.

Adbot
ADBOT LOVES YOU

Triple Tech
Jul 28, 2006

So what, are you quitting to join Homo Explosion?
I vaguely remember reading this in Perl Hacks or some such, but would it be good to focus on coding a type of Perl that didn't generate as many ops as say another method?

code:
my $a = "something";

# method 1, assignment
my $b = $a;

# method 2, stringify, assignment (more ops)
my $b = "$a";
Are less ops always faster than more?

mister_gosh
May 24, 2002

Triple Tech posted:

Two things. One, it sounds like what you're asking for is to output to a file as soon as possible. That is achieved by the following:

code:
$|++;
I'm fully aware that it looks crazy, but that's the way most Perl programmers write it. It sets the output autoflush variable to true. That means every time something gets sent to a filehandle, it will definitely show up. I don't think a handle needs to be closed to be written to this way, that's what I'm banking on.

The other thing is how to clean up a mess when you've been interrupted. You get around that with a signal handler. I believe the Ctrl-C signal is SIGINT. You override that handler with your code and it will be run every time someone interrupts your program. But that's probably not what you want to do here.

Thanks, this is invaluable stuff!

more falafel please
Feb 26, 2005

forums poster

Triple Tech posted:

I vaguely remember reading this in Perl Hacks or some such, but would it be good to focus on coding a type of Perl that didn't generate as many ops as say another method?

code:
my $a = "something";

# method 1, assignment
my $b = $a;

# method 2, stringify, assignment (more ops)
my $b = "$a";
Are less ops always faster than more?

Well, I wouldn't exactly call myself a Perl expert, but if the operations required to do A are a subset of the operations required to do B, then A is going to be faster. In this case, you have string scalar assignment versus string scalar interpolation (basically a strcpy()) and then string scalar assignment. Otherwise, it depends on the operations themselves.

In regards to the value of teaching one way or another... it depends. In your example I find method 2 to be less indicative of what's going on, so I certainly wouldn't suggest it. But just because one method isn't as fast as another doesn't mean you shouldn't use it -- unless it's causing you noticeable performance problems, I would stick with the way that makes your code the clearest. I've found this especially important in Perl, where it's easy to get yourself into the habit of writing executable line noise.

Subotai
Jan 24, 2004

Triple Tech posted:

Two things. One, it sounds like what you're asking for is to output to a file as soon as possible. That is achieved by the following:

code:
$|++;
I'm fully aware that it looks crazy, but that's the way most Perl programmers write it. It sets the output autoflush variable to true. That means every time something gets sent to a filehandle, it will definitely show up. I don't think a handle needs to be closed to be written to this way, that's what I'm banking on.


Why would you ever want to increment this instead of setting it to 1? Unless you are sharing it across threads or something and it is being used in the same manner a semaphore or something weird like that, you should just set it to 1.

Triple Tech
Jul 28, 2006

So what, are you quitting to join Homo Explosion?

Subotai posted:

Why would you ever want to increment [autoflush] instead of setting it to 1? Unless you are sharing it across threads or something and it is being used in the same manner a semaphore or something weird like that, you should just set it to 1.

Autoflush is just autoflush and it shouldn't be used for anything else (except maybe golfing and obfu). And it's written that way because that's just the way Perl people are.

code:
$| = 1; # too long
$|++;   # winnah
I guess I could make up a couple reasons. Well, it's shorter. Perl people love their terse. It's ... traditional, sort of. Also, it's not really an assignment. I'm not saying that the auto flush concept is "incrementable" but it doesn't really support arbitrary assignment, so the equals sign may be implying too much. Whatever, they're both equally bad, but one is less bad than the other.

Edit: Reviewing some posts in Perl Monks, I see that both are written, one not any less right than the other. But I would put my money on the ++ version being used more.

npe
Oct 15, 2004

mister_gosh posted:

I have a question. I have a filehandle I'm printing to:

code:
open(OUT, ">C:/example.txt");
...
print OUT "something";
...
close OUT
If someone CTRL-C's this script, nothing gets put in to C:/example.txt. Is there a way to ensure it closes properly or a better way of doing this?

Edit: thinking about this some more, is there a way to do something like if a user does CTRL-C or if there is an abrupt end or big error, can the program say "on exit, close this file handle?"

Override the SIGINT handler:

code:

 open(OUT, ">C:/example.txt");
 $SIG{INT} = sub{ close(OUT) };
 ...

Erasmus Darwin
Mar 6, 2001

Triple Tech posted:

Two things. One, it sounds like what you're asking for is to output to a file as soon as possible. That is achieved by the following:

code:
$|++;

Autoflush only works on the currently selected file handle, which by default is STDOUT. However, the following options should all work:

code:
use IO::Handle;

OUT->autoflush(1);
-or-

code:
$oldfh = select(OUT);
$| = 1;
select($oldfh);
-or-

code:
select((select(OUT), $|=1)[0]);

more falafel please
Feb 26, 2005

forums poster

Triple Tech posted:

I guess I could make up a couple reasons. Well, it's shorter. Perl people love their terse. It's ... traditional, sort of. Also, it's not really an assignment. I'm not saying that the auto flush concept is "incrementable" but it doesn't really support arbitrary assignment, so the equals sign may be implying too much. Whatever, they're both equally bad, but one is less bad than the other.

Edit: Reviewing some posts in Perl Monks, I see that both are written, one not any less right than the other. But I would put my money on the ++ version being used more.

I noticed this too, and my first thought was that, if any nonzero value of $| means autoflush, then maybe $|++ and $|-- are preferred to give stack semantics:
code:
$| = 1;
print_some_crap();
someone_elses_code();
print_some_crap();
$| = 0;

sub someone_elses_code
{
    $| = 1;
    print_some_crap();
    $| = 0;  # oh shi
}

leedo
Nov 28, 2000

mister_gosh posted:

I have a question. I have a filehandle I'm printing to:

code:
open(OUT, ">C:/example.txt");
...
print OUT "something";
...
close OUT
If someone CTRL-C's this script, nothing gets put in to C:/example.txt. Is there a way to ensure it closes properly or a better way of doing this?

Edit: thinking about this some more, is there a way to do something like if a user does CTRL-C or if there is an abrupt end or big error, can the program say "on exit, close this file handle?"

I've never had to do it, but you could try something like:
code:
open(my $out, '>', 'C:/example.txt');
$SIG{INT} = sub { close $out; };
print $out "something";
close $out;
Regarding autoflush I would probably do it this way, for the sake of whoever is going to be maintaining the code:
code:
use constant { TRUE => 1, FALSE => 0 };
$OUTPUT_AUTOFLUSH = TRUE;
edit: bleh beaten...

leedo fucked around with this message at 22:37 on Dec 7, 2007

Filburt Shellbach
Nov 6, 2007

Apni tackat say tujay aaj mitta juu gaa!

more falafel please posted:

I noticed this too, and my first thought was that, if any nonzero value of $| means autoflush, then maybe $|++ and $|-- are preferred to give stack semantics:
code:
$| = 1;
print_some_crap();
someone_elses_code();
print_some_crap();
$| = 0;

sub someone_elses_code
{
    $| = 1;
    print_some_crap();
    $| = 0;  # oh shi
}


Nope. $| is deeply magical. $|++ is equivalent to $| = 1. $|-- is equivalent to $| = 1 - $|.

more falafel please
Feb 26, 2005

forums poster

Sartak posted:

Nope. $| is deeply magical. $|++ is equivalent to $| = 1. $|-- is equivalent to $| = 1 - $|.

Ok, then I have no idea, other than terseness. What's the reasoning for that semantic?

Triple Tech
Jul 28, 2006

So what, are you quitting to join Homo Explosion?

Sartak posted:

Nope. $| is deeply magical.

What? I thought any non-zero value is funneled to 1 and all in/decrement operators work as expected (on either the numbers one or zero). I don't see any reason why the implementors would go out of their way to provide a different implementation to decrement.

Subotai
Jan 24, 2004

I have read a ton of Perl books and gone through lots of Perl code and have NEVER seen anyone increment it. I think it is bad form and confusing. :colbert:

Filburt Shellbach
Nov 6, 2007

Apni tackat say tujay aaj mitta juu gaa!

more falafel please posted:

Ok, then I have no idea, other than terseness. What's the reasoning for that semantic?

No idea. :)

Triple Tech posted:

What? I thought any non-zero value is funneled to 1 and all in/decrement operators work as expected (on either the numbers one or zero). I don't see any reason why the implementors would go out of their way to provide a different implementation to decrement.

code:
% re.pl
> $|
0
> $| = 100
1
> $| = -1
1
> $| = 0
0
> ++$|
1
> ++$|
1
> --$|
0
> --$|
1
> --$|
0

Triple Tech
Jul 28, 2006

So what, are you quitting to join Homo Explosion?
So, what did everyone think about the latest State of the Onion?

I'm still a believer... :(

leedo
Nov 28, 2000

I haven't really been following perl6 too closely, but I am excited to see him write about including multiple dispatch and some form of typing.

Ninja Rope
Oct 22, 2005

Wee.

mister_gosh posted:

I have a question. I have a filehandle I'm printing to:

code:
open(OUT, ">C:/example.txt");
...
print OUT "something";
...
close OUT
If someone CTRL-C's this script, nothing gets put in to C:/example.txt. Is there a way to ensure it closes properly or a better way of doing this?

Edit: thinking about this some more, is there a way to do something like if a user does CTRL-C or if there is an abrupt end or big error, can the program say "on exit, close this file handle?"

All file handles are always closed when your program exits. Are you sure that something else isn't going on when users ctrl+c out of the program?

Edit: A language reaches perfection when there is nothing left to take away, not when there is nothing left to add (similar to RFC1925). For that reason I'm a little worried about Perl6...

Ninja Rope fucked around with this message at 01:44 on Dec 9, 2007

npe
Oct 15, 2004

Ninja Rope posted:

All file handles are always closed when your program exits. Are you sure that something else isn't going on when users ctrl+c out of the program?

This is true but he wants the buffer flushed to the file first, which does not happen if you ctrl-c (at least on the systems I have available to me to experiment with).

Ninja Rope
Oct 22, 2005

Wee.

Satan's Scallion posted:

This is true but he wants the buffer flushed to the file first, which does not happen if you ctrl-c (at least on the systems I have available to me to experiment with).

I was under the impression that dirty write buffers are flushed when the handle is closed, but I don't really care enough to double check that. If we're sure that's what's happening, then you're right and the signal handler is the best way to go. However, I'd probably wrap the code that works on OUT inside a lexical block and use local $SIG{INT} = sub( close(OUT); exit; }.

Also, it's best to use actual variables to hold your file handles (eg, open($fh, 'file') instead of open(FH, 'file')).

npe
Oct 15, 2004

Ninja Rope posted:

I was under the impression that dirty write buffers are flushed when the handle is closed, but I don't really care enough to double check that. If we're sure that's what's happening, then you're right and the signal handler is the best way to go. However, I'd probably wrap the code that works on OUT inside a lexical block and use local $SIG{INT} = sub( close(OUT); exit; }.

This was based on experience and a short test, incidentally here's what I did:

code:
[~] $ cat sigint_me.pl
open(my $file, ">blargh.txt");
print $file "hello!";
sleep(1000);
[~] $ perl sigint_me.pl

[~] $ cat blargh.txt
[~] $
Interestingly, setting the handler to any sub at all seems to force the handle to be flushed, so I'm not entirely sure why that is. Setting it to "sub{exit}" forces a flush on my system.

quote:

Also, it's best to use actual variables to hold your file handles (eg, open($fh, 'file') instead of open(FH, 'file')).

Yes, I realize, I was simply tacking onto his example for clarity. :)

npe fucked around with this message at 05:28 on Dec 9, 2007

Triple Tech
Jul 28, 2006

So what, are you quitting to join Homo Explosion?

Ninja Rope posted:

Edit: A language reaches perfection when there is nothing left to take away, not when there is nothing left to add (similar to RFC1925). For that reason I'm a little worried about Perl6...

I don't understand what you're trying to say with this. By your logic, a stream of ones and zeros is perfect, because there's nothing left to take away. But that doesn't mean it's good for programming. Similarly, just because Perl 5 is pretty good on its own now doesn't mean it is immune from things to which it is insufficient in the future, like multi-methods and concurrency.

Ninja Rope
Oct 22, 2005

Wee.
That's pretty strange, I wonder if that has to do with how SIGINT is handled by default. Maybe Perl doesn't change the default SIGINT handler so when SIGINT is received Perl doesn't get a chance to flush its buffers, and the data never made it from Perl into the OS's buffers. But when you throw the exit into the signal handler, Perl does its whole shutdown routine as normal?

Anyway, you're right that if you need to insure some kind of behavior on SIGINT, a signal handler is the way to go. The only defined default behavior for SIGINT is to exit and anything outside of that should be explicitly added by the programmer.

I was actually mentioning the file handle thing more for mister_gosh (or anyone else using old bareword style handles). Since we're correcting one part of his program, we might as well correct everything about it. :)

Ninja Rope
Oct 22, 2005

Wee.

Triple Tech posted:

I don't understand what you're trying to say with this. By your logic, a stream of ones and zeros is perfect, because there's nothing left to take away. But that doesn't mean it's good for programming. Similarly, just because Perl 5 is pretty good on its own now doesn't mean it is immune from things to which it is insufficient in the future, like multi-methods and concurrency.

I think there has to be a balance, and I prefer when it leans more towards simplicity (that is, fewer builtins but a language flexible enough that 'advanced' features can be added by modules) than "kitchen sink", which Perl5 definitely seems to be now. However, it seems like some things are being added gratuitously to Perl5 (and 6), like the "say" function. We've already got print and $\, and printf, and they're adding another builtin to do something similar?

This is just an example, of course, but in my opinion (that of someone who does not design languages, merely uses them), it's just another function to remember and another reserved word. Yes, it might be a few characters shorter to say 'say "hi"' versus 'print "hi\n"', but is that really worth it?

Don't misunderstand, Perl5 is one of my favourite languages to use, but adding more features isn't always an improvement. For instance, in my mind, the removal of the "magic variables" ($|, $/, etc) would do a lot more to improve the language than adding more.

Triple Tech
Jul 28, 2006

So what, are you quitting to join Homo Explosion?

Ninja Rope posted:

is that really worth it?

Is it ever really worth it? Think about what programming languages have done since their inception; take more away so that we can do more. Programming languages will get higher and higher and enable us to see things that lower level languages haven't yet seen. I'm not saying higher level languages are a complete successor and substitute to lower level languages, but it helps keep your eye on what's really important: the work being done.

code:
# winnah
say for @items;

# sad panda
print "$_\n" for @items;
That's a trivial example. But you could ask if any of the features Perl6 is providing is worth it. I think they are, no matter what it is. If it brings us to a level where we can have an easier time discussing problems that were more complex today, I say go for it.

I never got why people are so opposed to Perl's way of handling things in all forms possible. No one is saying you can't do things a certain way. In fact, it's enabling the person do the work in whatever style they want. Of course people will then say oh it's hard to use someone else's code... Well, whatever. Work it out then. Talk about good practices. Or learn more about how different Perl looks.

Perl6 won't be perfect and it won't be for everyone... But I think it's the only language, that I know of (don't know many) that's really pushing the boundaries of making us more productive by providing use many, many tools. It isn't burdened by philosophical purity to the point of being unable to express a concept. Like if a language was completely void of multiple ways of saying things, I think it would just be a verbose mess.

And then verbosity gets into how people think in terms of chunks and lines of code, despite what language they're in... Terseness rules, Perl wins.

tef
May 30, 2004

-> some l-system crap ->

Triple Tech posted:

I don't understand what you're trying to say with this. By your logic, a stream of ones and zeros is perfect, because there's nothing left to take away. But that doesn't mean it's good for programming. Similarly, just because Perl 5 is pretty good on its own now doesn't mean it is immune from things to which it is insufficient in the future, like multi-methods and concurrency.

The original quote is "Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away." -- Antoine de Saint-Exuper

Or simply A perfect system is one with no unnecessary parts. It is often cited as an argument for minimalism and simplicity in design. You could also argue that a product with conceptual integrity has a small set of well chosen orthogonal features.

You could make the argument that while loops are unneccesary as we have for loops, if statements if we have conditional gotos - but it wouldn't be a very convincing argument. You could argue that brainfuck is perfection in terms of features removed, but not in terms of usable features left.

A similar quote might be "Make everything as simple as possible, but not simpler." -- Albert Einstein. Again we can see the theme of simplicity not being the bare minimum of what is needed, but also not having too much. Striking a balance is hard, and perl tends to err much more on the having too much (You could equally accuse other languages of being too simple).

I can't speak for him, but I guess his point is that Perl 6 might have too many features (or even featuritis). Perl has always been guilty of this in it's own polyglot way, though.

What other languages see as design choices, larry sees as developer choices:

Prototypes vs Class Based OO
Single vs Multiple Inheritance (and traits!)
Lazy vs Strict Evaluation
Static vs Dynamic Typing
And so on...

The problem here is that perl is becoming more of a series of dialects than a language itself. I often poked fun at people asking them if they coded basic in perl, c in perl or sh in perl - and it is becomming more true as more language paradigms are being embraced into perl 6.

Going back to the original quote: I think perl 6 would have had a better start if they removed features from perl 5 first before starting to add them. A lot of the changes (fixed sigils, simplified syntax) would have been possible to migrate into the existing code base.

The complete rewrite stalled all real progress until someone started to write it in haskell. I don't think larry was right to abandon the perl interpreter, and slowly but surely the perl5-porters are cleaning up the mess he left behind.

In summary: Minimalism and Simplicity are easy ways to maintain conceptual integrity in a product. Removing features can be more important than adding them. Perl 6 suffers from the second system effect.

Filburt Shellbach
Nov 6, 2007

Apni tackat say tujay aaj mitta juu gaa!

tef posted:

What other languages see as design choices, larry sees as developer choices:

Prototypes vs Class Based OO
Single vs Multiple Inheritance (and traits!)
Lazy vs Strict Evaluation
Static vs Dynamic Typing
And so on...

The problem here is that perl is becoming more of a series of dialects than a language itself. I often poked fun at people asking them if they coded basic in perl, c in perl or sh in perl - and it is becomming more true as more language paradigms are being embraced into perl 6.

To that I quote the recent State of the Onion:

Larry posted:

We don't see Perl 6 as a single language, but as the root for a family of related languages. As a family, there are shared cultural values that can be passed back and forth among sibling languages as well as to the descendants.

I think the idea is great. I do a lot of serious programming and Perl, and I'm very excited about being able to extend the language itself. Of course, maybe what I really want is a very very Perlish dialect of Lisp.

Ninja Rope
Oct 22, 2005

Wee.
code:
# winnah
say for @items;

# sad panda
print "$_\n" for @items;
I really do think that's needless. We have $\ specifically so you don't need 'say':
code:
local $\ = "\n";
print for @items;
Yes, that is still more characters to type, but this avoids creating a new builtin for every possible output record separator string.

Triple Tech posted:

And then verbosity gets into how people think in terms of chunks and lines of code, despite what language they're in... Terseness rules, Perl wins.

I disagree, maintainability and clarity rule (though that may be more an artifact of how I work and not indicative of the majority of Perl programmers). Adding more builtins increases terseness and clarity at the cost of a more complex language (and runtime, and parser) and smaller namespace. At a point you have to draw the line when to stop adding things, and I think say() was a good place to have drawn it. Builtins/keywords that help with multithreading/IPC are definitely welcome, though.

Edit: Agreeing with tef.

Ninja Rope fucked around with this message at 06:42 on Dec 9, 2007

tef
May 30, 2004

-> some l-system crap ->

Ninja Rope posted:

However, it seems like some things are being added gratuitously to Perl5 (and 6), like the "say" function. We've already got print and $\, and printf, and they're adding another builtin to do something similar?

I quite like say, I think it makes code more idiomatic and cleaner. It is not just about a few less characters, but making the code more obvious. You can see from the beginning if it is printing a new line or not.

Edit: $\ is not exactly a readable name. I imagine most people would use join(,) for adding record seperators. print "...\n" is really really common, and I don't think it is that bad to have a short hand.

Triple Tech posted:

And then verbosity gets into how people think in terms of chunks and lines of code, despite what language they're in... Terseness rules, Perl wins.

Remember: Code is much harder to Read than to Write. Perl excells at having short easy eays of writing idiomatic code, but it's a lot easier in perl to create things like this:

code:
for(<>){($f{$n}+=()=$t=~/gently caress/g)if($n,$t)=(/.{8}([^>]+)..(.*)/)}
$p{$f{$_}}.=":$_"for(keys%f);
print"$_$p{$_}\n"for(sort{$a<=>$b}keys%p)
Which, even with spacing and indentation:
code:
for (<>) {
 ($f{$n}+=()=$t=~/gently caress/g) if ($n,$t)=(/.{8}([^>]+)..(.*)/);
}

$p{$f{$_}}.=":$_" for (keys %f);

print "$_$p{$_}\n" for (sort{$a <=> $b} keys %p);
Is still pretty ugly. Neither Verboseness or Terseness is the objective of a good program, simplicity and clarity are.

(edit: double negative).

tef fucked around with this message at 17:32 on Dec 9, 2007

npe
Oct 15, 2004

Triple Tech posted:

And then verbosity gets into how people think in terms of chunks and lines of code, despite what language they're in... Terseness rules, Perl wins.

I won't get involved in the perl6 debate, but I want to address this. Perl is "more terse" for a limited set of things, but not all things. The biggest offender here is perl's support for OOP, which involves doing a lot of crap yourself and makes perl a lot more verbose.

Compare:

code:
package Foo;
use base 'Bar';

sub new
{
 bless {}, shift;
}

sub do_something
{
 my ($self, $arg1, $arg2) = @_;
 defined($arg1) or die "arg1 required";
 $arg2 ||= 'default_value';

 # do something
}
with python:

code:
class Foo(Bar):
    def do_something(self, arg1, arg2='default_value'):
        # do something
If you spend most of your time writing classes, perl loses the terseness war pretty quickly.

tef
May 30, 2004

-> some l-system crap ->

Satan's Scallion posted:

If you spend most of your time writing classes, perl loses the terseness war pretty quickly.

Aside: if you write a lot of oo perl, you might be interested in Moose: http://search.cpan.org/~stevan/Moose/lib/Moose.pm

code:
  package Point;
  use Moose; # automatically turns on strict and warnings

  has 'x' => (is => 'rw', isa => 'Int');
  has 'y' => (is => 'rw', isa => 'Int');

  sub clear {
      my $self = shift;
      $self->x(0);
      $self->y(0);
  }

  package Point3D;
  use Moose;

  extends 'Point';

  has 'z' => (is => 'rw', isa => 'Int');

  after 'clear' => sub {
      my $self = shift;
      $self->z(0);
  };
Edit: Pythons oo stuff is much cleaner though, I wish I had picked that as an example of terseness.

Edit 2:

Have you seen the perldelta for 5.10 ? http://search.cpan.org/~rgarcia/perl-5.10.0-RC2/pod/perl5100delta.pod It looks neat!

tef fucked around with this message at 07:19 on Dec 9, 2007

Triple Tech
Jul 28, 2006

So what, are you quitting to join Homo Explosion?
I'm not saying that Perl is the end-all-be-all of terseness and that terseness is the One True Dimension by which one judges code. Of course not, that's silly. But how I feel could be best expressed by reading this article by Paul Graham Yes, I have drank the cool-aid and I hope that's the right article...

It says (or should say) that the amount of effort a programmer puts towards programming N lines of code is constant, regardless of what programming language he uses. So, if you have a more verbose language, (Java) you will produce 1000 of code that only implements let's say one feature. But using a scripting language or something more flexible and possibly terse, you can produce 1000 lines of scripting that would implement three or four features. You're more productive that way.

Can you skew this test by jamming everything on one-line? No, I dont think you can. If you change the word from line to chunk, like a psychological chunk of thought, it makes more sense that way. People don't code in lines, they code in thoughts. It's like writing an essay. One run-on sentence doesn't help make your point any more clear. If Perl or some other agile language let's you encapsulate more and say more with less words, then you're more productive in it. I think this is a big win, because it helps me get real work done and that's what I'm all about.

And given your example in Python, I bet for fleshing out OOP concepts, Python would beat the pants off of Perl any day.

So I'm all for adding any feature that makes expressing certain concepts easier. Theoretically, you could run this into the ground and be like, well I made a language that's one character long ("1") and it is an accounts billing system! Well that's fantastic, that's the most productive accounts billing system programming language ever! But it's not flexible enough to be carried across different domains. So there's the key. What is it that you can add to a programming language to say less, but still remain flexible.

tef
May 30, 2004

-> some l-system crap ->

Triple Tech posted:

I'm not saying that Perl is the end-all-be-all of terseness and that terseness is the One True Dimension by which one judges code. Of course not, that's silly.

A bit different from "Terseness rules, Perl wins.". I think I will repeat myself here:

"Neither Verboseness or Terseness is the objective of a good program, simplicity and clarity are." (I missed out generality from that list.)

Terseness is not a useful measure of program quality at all - Clarity is a significantly better measure.

In the same way being able to implement something in a short amount of lines is terse, you would be better arguing that (in general) shorter programs are clearer and easier to read (as well as write) than longer ones. It is possible to write something too short though, again finding a balance between terseness and verbosity is essential. Simple things should be terse, but often complex things have to be verbose.

With regards to the Paul Graham article: (Again) "Code is much harder to read than to write".

If you are under the illusion that we should optimise languages so it is fast to write rather than read, I hope I never have to maintain your code.

quote:

What is it that you can add to a programming language to say less, but still remain flexible.

Again, adding features is not the be all and end all of language design. It is important to ask what can you remove from a language and still remain flexible?

There is a lot of baggage in perl left over from perl 1 to 4. An example in this thread is Bareword filehandles.

Adding more features does not always make a language more powerful. It can make the language more unwieldy.

Here is a pictorial argument:

This is the *actual* swiss army knife:


This is what happens when you add features, even if each tool itself is distinct and useful:



Edit: If you're still interested in arguing I would suggest we take this to a different thread.

Edit: I guess my point is that there is a limit to how many features you can add to a language before they become more of a hindrance, and sometimes languages become more useful by removing features.

tef fucked around with this message at 18:06 on Dec 9, 2007

npe
Oct 15, 2004

Triple Tech posted:


And given your example in Python, I bet for fleshing out OOP concepts, Python would beat the pants off of Perl any day.

So what you really mean is, "perl is more terse, except when it isn't"? What's the point of boasting about how perl is "more terse" and "wins" when you concede there are extremely large domains that it ends up being klumsy and verbose in?

vozz
Dec 11, 2005

vroom vroom
Why doesn't this work?

code:
sub randPw{
	my @dict = qw(A a B b C c D d E e F f G g H h I i J j K k L l M m N n O o P p Q q R r S s T t U u V v W w X x Y y Z z);
	my @pw;
	my $i = 0;
	my $numcount = $#dict + 1;
	while($i<$_[0]){
		$randNum = int(rand($numcount));
		$pw[$i] = $dict[$randNum];
		print($pw[$i]);
		$i++;
	}
}
randPw(7);

Triple Tech
Jul 28, 2006

So what, are you quitting to join Homo Explosion?

vozz posted:

Why doesn't this work?

Why doesn't what work? What is your code supposed to do, anyway? Are you getting error messages? :confused: :effort:
code:
my @dict = ('A' .. 'Z', 'a' .. 'z');
Also, if you're never redifining your dictionary, it should be a global.

vozz
Dec 11, 2005

vroom vroom

Triple Tech posted:

Why doesn't what work? What is your code supposed to do, anyway? Are you getting error messages? :confused: :effort:
code:
my @dict = ('A' .. 'Z', 'a' .. 'z');
Also, if you're never redifining your dictionary, it should be a global.

It's supposed to generate random strings based on @dict. And I'm trying to get this to work on my web server, not the command line.

fansipans
Nov 20, 2005

Internets. Serious Business.

vozz posted:

It's supposed to generate random strings based on @dict. And I'm trying to get this to work on my web server, not the command line.

Do you really want it to print out each character? Are you expecting it to return a value? Each letter it generates is immediately printed out, and not returned.

You could just add:
code:
return "@pw"
Which would stringify it, or return @pw which would return the array - be careful though because when @pw is evaluated in scalar context it returns the size of the array, not a nice happy string.

What I mean by this is that "my $password = randPw(7)" would assign the length of the returned array to $password, which is the number 7.

Here's a slightly less verbose implementation, that uses the same "iterate through the allowed characters" idea:

code:
sub randPw {
  my $len = shift;
  my @a=("A".."Z","a".."z");
  my $s;
  $s .= $a[rand(@a-1)] for 1..$len;
  return $s;
}

fansipans fucked around with this message at 19:40 on Dec 10, 2007

6174
Dec 4, 2004
My knowledge of Perl is limited as I really just use it as a duct tape language, or if a CPAN module looks convenient for whatever I'm trying to accomplish. I was writing a script last night that uses Net::Amazon to query prices and I think I found a bug, but before I harass the author I thought I'd post here for someone to confirm I'm not just doing something stupid.

code:
#!/usr/bin/perl

use strict;
use warnings;

use Net::Amazon;
use Net::Amazon::Request::ASIN;

#use Log::Log4perl qw(:easy);
#Log::Log4perl->easy_init($DEBUG);

my $ua = Net::Amazon->new(
    token       => "144RR0T0YM45X6SVKSR2",
    max_pages   => 5,
    strict      => 1,
);

my $req = Net::Amazon::Request::ASIN->new(
    asin => "0596000278",
);

my $resp = $ua->request($req);

if ($resp->is_success()) {
    for ($resp->properties()) {
        print "Product Name: ",$_->ProductName(),"\n",
            "List Price: ",$_->ListPrice(),"\tOur Price: ", $_->OurPrice(),
            "\tASIN: ",$_->ASIN(),"\n",
            "Availability: ",$_->Availability(),"\t";
        if ($_->SuperSaverShipping()) {
            print "Eligible for super saver shipping\n";
        } else {
            print "NOT eligible for super saver shipping\n";
        }
    }
} else {
    print "Error: ",$resp->message(),"\n";
}
(This uses the AWS Access key from here, but can/should be run under your own key if you have one)

Now the problem is the call to ListPrice() is always the same as OurPrice(), which is supposed to be the price Amazon is selling the item for. I think this is a bug because looking at Property.pm, lines 32 and 38 seem to be referring to the same data. Now it is possible that it is reassigned elsewhere, but I haven't found where if it does.

Adbot
ADBOT LOVES YOU

Kakesu
Nov 4, 2005

ETHICAL.

I have an incredibly annoying problem that is completely stumping myself and some other perl users at work, that I'm really hoping somebody can help with. I'm using ActivePerl in windows, and the script in question is designed to run a build process automatically. The script runs on two separate PCs, alternating back and forth so that there's a constant stream of new builds. None of this is really relevant to the problem, but I thought some background would be nice.

The problem is this: at one point in the script, the Windows "mkdir" command is called using a system() call. On ONE MACHINE ONLY, this fails, regardless of the location of the directory that is being created. The other machine executes the command just fine. The actual script creates a directory on another machine over the network, but I've tested it with local directories, and the same failure happens. Running the mkdir from a Windows command prompt works fine in both cases.

The line of code in question is this:
code:
system("mkdir \"\\\\machine-name\\shared_directory\\directory_to_create\"");
From my testing, it appears that the backslashes in the path aren't all escaping properly. The error that is thrown indicates that perl is trying to run the following command when this is run:
code:
mkdir "\\machine-name\\shared_directory\\directory_to_create"
The first backslashes escape as they're supposed to, but the ones later on in the path don't. Just for shits and giggles, I tried replacing those with single backslashes in the script, and got the following:
code:
mkdir "\\machine-nameshared_directory\directory_to_create"
The second set disappears completely, but the third displays the way that we originally wanted it to (even though it shouldn't).

We've tried re-installing Perl, using a different version of Perl, rechecking permissions, etc. Nothing seems to make any difference. Has anyone seen anything similar to this before, or have any ideas why a string that would be parsed normally on one machine, would be parsed completely differently on another machine running an identical Perl install?

  • Locked thread