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
Mithaldu
Sep 25, 2007

Let's cuddle. :3:

Voltaire posted:

i have.
Why do you use 8-space tabs then and start a new line for the opening brace of your blocks?

Voltaire posted:

im not even sure where to start with this one without using split and join.
In that case i can honestly say that you need to do some studying. Read the first two chapters of this, completely: http://perldoc.perl.org/perlre.html

Oh, and if you're going to be in IT professionally, start reading this website daily, starting from now: http://thedailywtf.com

And on another note: I think the intent of the exercise is to check if you're actually a Perl programmer or a C(++/#) programmer. Perl has some really powerful tools that C programmers often don't really know about and ignore, as it also has everything they're already used to. As such C programmers trying to do Perl often do more damage than a complete Perl newbie would do.

Mithaldu fucked around with this message at 22:10 on Nov 9, 2008

Adbot
ADBOT LOVES YOU

Filburt Shellbach
Nov 6, 2007

Apni tackat say tujay aaj mitta juu gaa!
What exactly do they forbid or allow? I ask out of curiosity; I'm not going to post a solution for you. The task is yours alone.

ashgromnies
Jun 19, 2004

Voltaire posted:

I'm having difficulty writing a program that determines whether a 7 character input is a character. I am not allowed to use arrays, reverse, split, join; just basic perl functions.

So far I have

code:
use strict;
use warnings;
use diagnostics;

print "Enter in a 7 character item: ";
chomp (my $input = <> );

$input =~ s/\\s//g;
if ($input = [9,8,7,6,5,4,3,2,1,0] == [0,1,2,3,4,5,6,7,8,9])
{
        print "PALINDROME!\n";
}
else
{
        print "NOT A PALINDROME!\n";
}
Obviously I'm missing something here...

Here's a naive solution for it, purposefully done poorly:

code:
[spoiler]
#!/opt/perl/bin/perl

use strict;
use warnings;

my $str = "banana";

print "is $str palindromic? ".&is_palindrome($str)."\n";

$str = "racecar";

print "is $str palindromic? ".&is_palindrome($str)."\n";


sub is_palindrome {
    my ($str) = @_;
    
    my $orig = $str;
    my $rev;

    while (my $chr = chop $str){
        $rev .= $chr;
    }

    return ($rev eq $orig) ? 1 : 0;
}
[/spoiler]
However, they most likely want you to use regular expressions to solve it.

Voltaire
Sep 20, 2003
The lunatic is in my head...
Im thinking on this one im not matching enough characters

code:
my ($input);
print "Enter in a 7 character item: ";
chomp ($input = <>);


if ($input =~ /\([A-Za-z0-9_]\)\([A-Za-z0-9_]\)\([A-Za-z0-9_]\)[A-Za-z0-9_]\03\02\01/){

        print "PALINDROME!\n";

}
else
{
print "NOT A PALINDROME!\n";

}

toadee
Aug 16, 2003

North American Turtle Boy Love Association

I did it a lot shorter than that but I was going on your initial post of "7 characters"

Filburt Shellbach
Nov 6, 2007

Apni tackat say tujay aaj mitta juu gaa!

ashgromnies posted:

&is_palindrome($str)

You do know that & is no longer required on function calls right?

heeen
May 14, 2005

CAT NEVER STOPS
Behold my palindrome test:
code:
use strict;
use warnings;
chomp (my $input = <> );
while($input=~/(.)(.*)\1/)
{
print "palindrome!\n" if length($2) <= 1;
$input=$2;
}

toadee
Aug 16, 2003

North American Turtle Boy Love Association

heeen posted:

Behold my palindrome test:

errr...

my shell posted:

> ./pdrome.pl
lalalal
palindrome!
> ./pdrome.pl
notone
palindrome!
> ./pdrome.pl
huh?
palindrome!

heeen
May 14, 2005

CAT NEVER STOPS
whoops forgot to add start and end markers to the regexp.
code:
use strict;
use warnings;
chomp (my $input = <> );
while((undef,$input) = $input=~/^(.)(.*)\1$/)
{
print "palindrome!\n" if length($input) <= 1;
}

toadee
Aug 16, 2003

North American Turtle Boy Love Association

Much better. Neat little algorithm that is!

leedo
Nov 28, 2000

This seems more clear, but I guess it is probably slower:
code:
my $string = "lolol";
print "palindrome" if $string eq join '', split //, reverse $string;
edit: vvv I have a rare talent for not reading instructions

leedo fucked around with this message at 21:27 on Nov 14, 2008

Triple Tech
Jul 28, 2006

So what, are you quitting to join Homo Explosion?
Wow, using every function he was asked to not use, nice.

Filburt Shellbach
Nov 6, 2007

Apni tackat say tujay aaj mitta juu gaa!

leedo posted:

$string eq join '', split //, reverse $string

reverse in scalar context will reverse the characters in the string. So just

$string eq reverse $string

is enough.

leedo
Nov 28, 2000

Whelp, i suck :(

Filburt Shellbach
Nov 6, 2007

Apni tackat say tujay aaj mitta juu gaa!
Now you suck a little less. ;)

We're all always learning. Don't sweat it.

Fenderbender
Oct 10, 2003

You have the right to remain silent.
I typed this.

code:
$string = "racecar";

while ($string =~ s/^(.)(.*)\1$/$2/) {
  print "PALINDROME" if length($string) <= 1;
}
Edit: Kinda similar to heeen's, it would seem.

Fenderbender fucked around with this message at 22:12 on Nov 14, 2008

Ninja Rope
Oct 22, 2005

Wee.

Fenderbender posted:

I typed this.

I went with:
code:
print "It's a seven character palendrome!\n" if $string =~ /^(.)(.)(.).\3\2\1$/;
So, did you get the job?

Mithaldu
Sep 25, 2007

Let's cuddle. :3:
Not a question, but something i just found out and thought i'd share:

Ever tried iterating through a hash so you could do something each value in it? The usual solution is to do:
code:
for my $key (keys %hash) {
    my $a = $hash{$key};
}
However, what if you don't actually care what the key is and ONLY care about the values? Perl provides something for that too, which is much more elegant and 4 times faster:

code:
for my $value (values %hash) {
    my $a = $value;
}

Triple Tech
Jul 28, 2006

So what, are you quitting to join Homo Explosion?
code:
my @altered_values = map { transform($_) } values %hash;

my $accumulator;
$accumulator += $_ for values %hash;

Mithaldu
Sep 25, 2007

Let's cuddle. :3:
Am i doing something wrong or is map really slow?

code:
say scalar values %hash;

timethese( 160, {
        'map' => sub {
            my @array;
            @array = map { ++$_ } values %hash;
        },
        'loop' => sub {
            my @array;
            for my $value (values %hash) {
                push @array, ++$value;
            }
        },
    }
);

__END__

39144
Benchmark: timing 160 iterations of loop, map...
   loop: 1.5823 wallclock secs ( 1.58 usr +  0.00 sys =  1.58 CPU) @ 101.39/s (n=160)
   map: 2.81493 wallclock secs ( 2.78 usr +  0.02 sys =  2.80 CPU) @ 57.20/s (n=160)

TiMBuS
Sep 25, 2007

LOL WUT?

Mithaldu posted:

Am i doing something wrong or is map really slow?

Well yeah pretty much the latter. For starters, I think foreach is optimized to zip over temporary lists in a less eager fashion. map also needs to create a temporary list and then possibly copy it to @array, and the code block passed to it probably incurs some overhead being called every time compared to a foreach block.
Whatever the cause I can say for certain map takes more memory (I just nearly killed my PC testing that) which means more copying is involved so its definitely slower.

mister_gosh
May 24, 2002

I have an incredibly basic Perl and IO stuff in general question.

I have a database related app that takes about 4 minutes to run. While it does so, it some known variable values to the screen.

I just ran this same program but told it to not print the messages and it took only 2 minutes. Nothing is different. The same variables are being collected. The only difference is I am not executing the print statements.

What the heck? Does it really take half of the time to print my variables?

I'm not sure how much data is sent to the screen during one submission, but I would guess 2MB at most.

Mithaldu
Sep 25, 2007

Let's cuddle. :3:
2MB @ 80 line length is about 25000 lines. 50000 lines at a more likely medium length of 40. Depending on your CPU, that can make a good bit of difference. Also important to think about is: What *exactly* is it printing? How much data does it have to pull from the memory per print? How many references does it have to resolve per variable? etc. etc.


TiMBuS posted:

map performance sucks
Thanks. That's the perfect answer i needed to never again bother with map at all. :D

Triple Tech
Jul 28, 2006

So what, are you quitting to join Homo Explosion?

Mithaldu posted:

Thanks. That's the perfect answer i needed to never again bother with map at all. :D

It's this sort of knee-jerk reaction I really despise among developers. Map isn't inferior to for in every regard and can provide some very special benefits. Thinking that performance is the end-all be-all of feature's usage is to not really understand either performance or the feature. So shame on you, etc.

Mithaldu
Sep 25, 2007

Let's cuddle. :3:
It's not a kneejerk reaction at all. For some reason i have serious problems wrapping my head around map and just plain reading it, as opposed to a for loop. My brain keeps expecting a comma or some parantheses. I also, to some extent, dislike the use of "magic variables" like $_ or functions that implicitly use it. As such, i have never seen map having any readability advantage for me at all.

Additionally i have, over the last few years, never had any need to iterate over an array, do something simple enough to fit into one line with map and then retain it while creating a new array for the output.

I have literally been looking for advantages of it over the past two weeks and aside from it being a different syntax (which is a disadvantage for me) i have found exactly none. It being slower than for only drives the nail in its coffin of uselessness for me.

TL;DR: Don't jump to conclusions and accusations so quickly, eh?

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

mister_gosh posted:

What the heck? Does it really take half of the time to print my variables?

I'm not sure how much data is sent to the screen during one submission, but I would guess 2MB at most.

Console I/O is extremely slow, and I am not at all surprised by the idea that dumping 2MB of data to the console might take two minutes to resolve. As an experiment, try running the same program with output redirected to a file or to /dev/null; if suppressing all output runs in t, I predict the former will clock in at t+5s and the latter will be almost exactly t.

EVIL Gibson
Mar 23, 2001

Internet of Things is just someone else's computer that people can't help attaching cameras and door locks to!
:vapes:
Switchblade Switcharoo
This code uses LWP to follow redirects. I will handle the redirects better in the future but does anyone know why I can't print out the location where the random link takes me?

code:
#!/usr/bin/perl -w
use strict;
use LWP;



 my $ua = LWP::UserAgent->new;
  $ua->agent("MyApp/0.1 ");

  # Create a request
  push @{ $ua->requests_redirectable }, 'POST';
  #my $req = HTTP::Request->new(POST => 'http://www.randomwebsite.com/cgi-bin/random.pl');
  my $req = HTTP::Request->new(POST => 'http://random.yahoo.com/bin/ryl');
  $req->content_type('application/x-www-form-urlencoded');
  $req->content('query=libwww-perl&mode=dist');

  # Pass request to the user agent and get a response back
  my $res = $ua->request($req);

  # Check the outcome of the response
  if ($res->is_success) {
      print $res->content;
  }
  else {
      print $res->status_line, "\n";
  }
  
  print  $res->header('location');


ShoulderDaemon
Oct 9, 2003
support goon fund
Taco Defender

EVIR Gibson posted:

This code uses LWP to follow redirects. I will handle the redirects better in the future but does anyone know why I can't print out the location where the random link takes me?

Because the final response, which is what you're examining, was not a redirect, so it does not have a Location header.

You probably want $res->request->uri, which should return the URI of the request that actually generated the final response.

fansipans
Nov 20, 2005

Internets. Serious Business.

Mithaldu posted:

I have literally been looking for advantages of it over the past two weeks and aside from it being a different syntax (which is a disadvantage for me) i have found exactly none. It being slower than for only drives the nail in its coffin of uselessness for me.

It makes code a hell of a lot more readable ...

code:
my @names = qw/alice bob carol dan/;
my @name_lengths = map { length } @names;

Mithaldu
Sep 25, 2007

Let's cuddle. :3:

fansipans posted:

It makes code a hell of a lot more readable ...
Not to me. Looks more like perl golf than anything else.

Edit: I think my problem is that i mentally translate every code i see into actual english sentences. That works very well for most constructs of Perl unless golfed. Map is impossible for me to translate into an english instruction.

Mithaldu fucked around with this message at 15:45 on Nov 18, 2008

fansipans
Nov 20, 2005

Internets. Serious Business.

Mithaldu posted:

Not to me. Looks more like perl golf than anything else.

Edit: I think my problem is that i mentally translate every code i see into actual english sentences. That works very well for most constructs of Perl unless golfed. Map is impossible for me to translate into an english instruction.

That reminds me of learning Spanish back in High School.

There were kids who did all their homework, memorized every word in the book, and got straight A's. But when it came time for spoken exams, you'd see their eyes roll up to the ceiling, and the words come out one at a time.

Then there were a few kids that could flip a switch, and speak almost entirely in Spanish. They'd often have a few pet phrases that they'd incessantly discuss in a variety of situations. Mine was "vaca", the word for cow. "The cow has gone to the police station to complain about the loud children and their annoying cars", "The drunken cow sang a song using the broccoli as a microphone", etc. These kids would accidentally keep speaking Spanish when they left class. They might not remember the word for brakes on a car, but instead they'd just say "la machina para hacer parar" (the machine to make to stop)

Both types of student could certainly survive if stranded in Madrid or Mexico City, but the latter would probably have much more fun :)

Mithaldu
Sep 25, 2007

Let's cuddle. :3:
I'm not entirely sure what you're trying to say with that, but honestly, I'd see myself as the latter kind of guy. When i read my Perl code it is really just *reading*, like one would usually do with a book. I see the code and effortlessly know the intent of the instruction. Certain things however just gently caress with that flow, so i work around them. It's not that i can't do it, it's just that they slow me down too much.


I know what it does, but that reading seems entirely backwards to my mind.
vvvv

Mithaldu fucked around with this message at 17:17 on Nov 18, 2008

npe
Oct 15, 2004
It's funny, because for many people (myself included), the functional approach of map seems much easier to translate into english.

code:
my @name_lengths = map { length } @names;
In pseudo code that's something like:
code:
 "Name lengths" is a list of the lengths of "names". 
It's descriptive, as opposed to a set of instructions, which is much more natural-language like. YMMV I suppose.

tripwire
Nov 19, 2004

        ghost flow

Mithaldu posted:

It's not a kneejerk reaction at all. For some reason i have serious problems wrapping my head around map and just plain reading it, as opposed to a for loop. My brain keeps expecting a comma or some parantheses. I also, to some extent, dislike the use of "magic variables" like $_ or functions that implicitly use it. As such, i have never seen map having any readability advantage for me at all.

Additionally i have, over the last few years, never had any need to iterate over an array, do something simple enough to fit into one line with map and then retain it while creating a new array for the output.

I have literally been looking for advantages of it over the past two weeks and aside from it being a different syntax (which is a disadvantage for me) i have found exactly none. It being slower than for only drives the nail in its coffin of uselessness for me.

TL;DR: Don't jump to conclusions and accusations so quickly, eh?

No, he has a point. I know on lifevis you are concerned chiefly with optimizing the performance but its a big mistake to just decide you are never going to care to learn about functional programming. Even though I don't understand it particularly well, its helped me a lot on seeing problems in a new light

If/when you really get the hang of map and lamba calculus a whole bunch of things will slide into place mentally and you'll start addressing a lot of problems in a new way. There could be bottlenecks in your lifevis code that would disappear if you formulated a functional solution, for example.
The ability to not care about state and getting parallization for free easily make functional programming worth learning about.

Mithaldu
Sep 25, 2007

Let's cuddle. :3:
I didn't say anything about functional programming, just about map in the context of Perl. :)

In fact, i have this on my "to read" list: http://gigamonkeys.com/book/

tripwire
Nov 19, 2004

        ghost flow

Mithaldu posted:

I didn't say anything about functional programming, just about map in the context of Perl. :)

In fact, i have this on my "to read" list: http://gigamonkeys.com/book/

Oh, well ignore me then. I've noticed that Map is slow in python as well, at least compared to list comprehensions.

I Am Quaid
Dec 12, 2005
Add onion rings to any meal deal for €1
I'm having a problem using a class I wrote in a different file (in the same folder). When I try to run 'nodeTest.pl' which just tries to call the class constructor which is contained in the class definition in 'WorkerNode.pm'.

code:
quaid:/home/quaid/TrainBooker/WorkerNode# perl nodeTest.pl
WorkerNode.pm did not return a true value at nodeTest.pl line 5.
BEGIN failed--compilation aborted at nodeTest.pl line 5.
Am I doing something wrong?

Thanks in advance!

Ninja Rope
Oct 22, 2005

Wee.
Modules need to return a "true" value to indicate they loaded successfully. However, since the main body of code in a module isn't inside a function, you can't actually use a "return" statement, you need to place a statement at the end of the module that implicitly returns a true value.

In short, add
code:
1;
to the bottom of WorkerNode.pm.

tef
May 30, 2004

-> some l-system crap ->

Mithaldu posted:

In fact, i have this on my "to read" list: http://gigamonkeys.com/book/

Higher order perl by mjd is well worth a read too.

Adbot
ADBOT LOVES YOU

Mario Incandenza
Aug 24, 2000

Tell me, small fry, have you ever heard of the golden Triumph Forks?
http://returnvalues.useperl.at/

42 seems to be another commonly used one.

Mario Incandenza fucked around with this message at 07:00 on Nov 19, 2008

  • Locked thread