Showing posts with label subroutine. Show all posts
Showing posts with label subroutine. Show all posts

Friday, January 9, 2009

Questions Regarding Perl References In Linux And Unix

Hey There,

Today's post is a follow up to our post, from earlier this week, regarding understanding Perl variable references. The feedback was generally positive, but one particular question was asked by quite a few people. And that question was:

If there's nothing new under the sun, then how can there be more things in heaven and earth than are dreamt of in anyone's philosophy?

To be quite honest, I have no idea. I quit pondering the meaning of "it all" when I was introduced to nihilism at the age of 18, which, consequently, fit in perfectly with my intensive practical application of Onanism. My philosophy was both fun "and" meaningless ;)

But, that wasn't the real question. I just went off on a tangent there for a moment, as it's my wont to do. Apologies for any trauma caused by the high-brow self-abuse joke. It has nothing to do with Linux, Unix or Perl unless you, like Sammy Hagar, consider it all mental masturbation ;)

The real question on people's minds was this:

What purpose, at all, do references in Perl serve, and why would I ever want to complicate things by using them?

This is a valid question; especially if you aren't hard-core into Perl or only use it as a work aide. Quite frankly, I, myself, rarely have any use for references. But here's a quick rundown of a few reasons why it's good to know them and understand how they work (Note that, in Perl, references and pointers - as they're more commonly known in programming languages like C - are terms that often get used interchangeably. For our purposes, they both mean the same thing).

1. For folks who've been using Perl since version 4 and earlier, references were an absolute "must" to understand if you wanted to do any semi-complex work with subroutines. At that point in time, you could only pass scalar variables as arguments to a subroutine. This made it impossible for you to, for instance, pass an array, hash or more complex variable as an argument to your subroutine. Thus, the reference made it possible for you to pass an array or hash as an argument to your subroutine, since the Perl reference to either was (and is) always a scalar variable. I think this is the one issue that is really being addressed when folks question the usefulness of Perl references these days. As the below scriptlet shows, the days of only being able to pass a scalar variable to your subroutines are long since gone. The language has been improved upon and, now, you can pass arrays, hashes, etc, directly to your subroutines as arguments, without having to make use of scalar references to them (more on that in point 2). Check out the following for a demonstration of how Perl can now handle these types of arguments (a few of you actually already have this in your mail, as I put it together to demonstrate this principle earlier this week in response to several emails - I aim to please :):

host # cat shell.pl
#!/usr/bin/perl

$bfile = "what the heck";
@bfile = qw(what the heck);

scalarsub($bfile);
arraysub(@bfile);

sub scalarsub {

my $file=shift;
print "SCALAR: F $file\n";
}

sub arraysub {

my @file=@_;
foreach $item (@file) {
print "ARRAY: F $item\n";
}
}
--- test run of script ---------
host # ./shell.pl
SCALAR: F what the heck
ARRAY: F what
ARRAY: F the
ARRAY: F heck


As you can see, above, today's Perl doesn't require you to reference non-scalar variables if you want to pass them as arguments to a subroutine.

2. References still do have a place in Perl, even when it comes to subroutines. If it sounds like I'm contradicting what I just wrote, please allow me to dig myself further into a hole... I mean, explain ;)

Consider, if you will, the following situation in which making use of Perl references would actually save you considerable time and, probably, a gray hair or two. If you have a simple subroutine (like in our scriptlet above), it is very easy to pass it several scalar arguments (assuming no restrictions on the amount of arguments you can pass) and, logically, any amount, and/or combination, of different types of variables. But, what happens when you call your subroutine with arguments like this?:

@array1 = qw(1 2 3 4 5);
@array2 = qw(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19);
@array3 = qw(1 2 3);
mynewsubroutine(@array1, @array2, @array3);
@_ = 1 2 3 4 5 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 1 2 3;
<-- within your subroutine.
my (@array1,@array2,@array3) = @_;

Now, while there are more than several clever ways you can get around parsing this input (which is one of the great things about Perl), it can be difficult to process this sort of input within the subroutine; especially if the arrays, themselves, are of variable and/or undetermined size (perhaps @array1 contains 5 scalar variables, @array2 contains 19 scalar variables and @array3 contains an additional 3 scalar variables - we'll, again, stay away from passing arrays of hashes of arrays for now ;). This can constitute a lot of work on the programmer's part to craft the subroutine in such a way that it handles all of the input and keeps it separated, correctly, into the three groups, since the totality of the arguments passed to a subroutine can be referenced by @_ and, if three separate arrays are passed, @_ will contain all 3 of them (27 scalar variables) and you can't separate them by index @_[0], etc, since the input to your subroutine is, in effect, one large array, rather than a collection of 3 smaller arrays. In effect, and in reality, your subroutine would put all of the members of all of the 3 arrays into @array1.

Hopefully, I'm not drifting too far off of the reservation, here, as I fear I'm wandering into the land of overly convoluted explanation again ;) The advantage to you, the programmer, in this instance, would be that you could use Perl references to pass scalar references to each array to your subroutine. As difficult as it would be to manage the above three arrays using straight passing to your subroutine (you would have to determine their size before passing them in and then keep track of that by passing even more information, not to mention re-allocating those members back into the subroutine's local arrays), it would be a bit easier to pass your subroutine three references to your three arrays, like so:

mynewsubroutine(\@array1, \@array2, \@array3);

Now, the reason this makes life easier for you is that you're only passing your subroutine 3 scalar variables, rather than an indeterminate amount of any other kind. Inside the subroutine, you can easily work with the variables using the dereferencing techniques we went over in our understanding Perl references post. For instance, you could do "foreach" on all 3 arrays separately, and process the internal array variables that way, effectively making the size of any of those arrays inconsequential (less work for you), like so:

my $array1 = shift;
foreach $thingy (@{$array1}) {
print "Thingy $thingy\n";
}


I'm oversimplifying to a certain degree, but this is getting out of hand just swimmingly in spite of my best efforts ;)

3. Although I promised I wouldn't go here, I must (but I'll keep it theoretical so we can dispense with it post-haste). If you ever do any super-complex programming, like building matrices, doing crazy manipulation of filehandles (remember that "any" Perl data type can be referenced) or things along the nature of manipulating arrays of hashes of multiple nested arrays of hashes, using references can make it a lot simpler for you to keep your head from exploding (which is a lousy way to end the day ;)

Hopefully, these answers have been somewhat helpful, and/or illustrative regarding the question at hand (why use references at all, and are they even really necessary?) If you're interested in reading more on the subject, check out Chapter 18 of bjnet.edu.cn's introduction to Perl. It's written very well and is probably simpler to follow than my meandering over-explanations ;) Plus, all the other chapters are available online, so you could download them all and have yourself a very nice free Perl reference in however long it takes you to download the HTML.

Cheers to all, and thank you for your response to the post that spawned this one. There's nothing quite so rewarding as knowing that I'm actually writing something at least a few people are really interested in reading :)

, Mike




Discover the ClickBank affiliate program that pays 100% commission!



Please note that this blog accepts comments via email only. See our Mission And Policy Statement for further details.

Thursday, September 18, 2008

Streamlined Perl Number Matching Script For Unix Or Linux

Hey There,

We'll, this week's been completely out-of-sequence. Today's post was slated for the day before yesterday and Tuesday's number pool script that was supposed to come out yesterday ended up getting published on Tuesday. If there's one thing we've learned this week, it's that my day job is starting to interfere with my hobbies ;)

On the bright side, we're finally getting around to wrapping up the two-parter we started on Monday with our uncondensed Number Matching Perl Script. The intent, with that post, was to show a working example of a simple Perl script (basically, matching numbers out of another file with a few option-based limitations imposed by the user) that was written off-the-cuff. Although it functioned, and worked pretty efficiently, it was a confusing mess to look at, and didn't include some options that it probably should have. To summarize, the aim of the follow up post (today's, at last) was going to be to reproduce that script in a more condensed format. This condensation (that just doesn't sound right, does it? But, I looked it up in the dictionary and the way in which I meant it was actually the first entry ;) would include addition of extra code to handle some needed functionality, as well as a few helpful comments and more logical ordering of all the parts. The end result, hopefully, is more scalable, so you won't have to dread all the extra typing and logical convolution involved in adding a seventh variable ;)

Again, we have the same fairly simple Perl script that will parse any file consisting of rows of numbers and print out matches meeting certain criteria. As noted before, you can visit the lamer version of this script from Monday and compare it with today's "better" version (or "less lame," depending on what kind of a person you are. Glass half full? Glass half empty? Glass too big? ;)

Again, the basic file format (for the input) should be a text file with lines like the following (note that this updated script will also take regular single digits and has an extra "-p" flag if you want to pad those with 0's):

host # cat file
01 02 03 04 05 09
5 18 19 45 33
33 55 666 88 23 12
...



Again, the script has 4 non-optional arguments that you'll be prompted for if you forget to enter any of them (with the additional, and optional, "-p" flag), like so:

host # ./match.pl
Error Encountered! Invalid or incomplete options!
Usage: ./better.pl -h highNumber -f statFile -n numberOfCombos -m mimimumCombos
[-p padSingleDigitsWithZeros]


A regular execution would look like this (we're removing duplicate match elements in a simple hash now, instead of building an increasingly lengthening logic knot - depending upon how you want to implement the match, it should be trivial, like adding \b or whatnot, to make the matches more exact so that 13 won't match 130):

host # ./match.pl -h 15 -f NUMFILE -n 3 -m 10 -p
12 matches 10 times:
7 8 9 10 11 12
109 110 111 112 113 114
115 116 117 118 119 120
121 122 123 124 125 126
127 128 129 130 131 132
211 212 213 214 215 216
307 308 309 310 311 312
409 410 411 412 413 414
511 512 513 514 515 516
607 608 609 610 611 612

13 matches 10 times:
13 14 15 16 17 18
109 110 111 112 113 114
127 128 129 130 131 132
133 134 135 136 137 138
139 140 141 142 143 144
211 212 213 214 215 216
313 314 315 316 317 318
409 410 411 412 413 414
511 512 513 514 515 516
613 614 615 616 617 618

15 matches 10 times:
13 14 15 16 17 18
115 116 117 118 119 120
145 146 147 148 149 150
151 152 153 154 155 156
157 158 159 160 161 162
211 212 213 214 215 216
313 314 315 316 317 318
415 416 417 418 419 420
511 512 513 514 515 516
613 614 615 616 617 618


And, when everything isn't equal, the output basically looks the same :)

host # ./match.pl -h 15 -f NUMFILE -n 3 -m 5 -p

01 02 matches 6 times:
97 98 99 100 101 102
199 200 201 202 203 204
301 302 303 304 305 306
397 398 399 400 401 402
499 500 501 502 503 504
601 602 603 604 605 606...


All in all, we only save about 50 lines of code (some of which is blank lines and comments), but the result should be a lot easier to manage and build upon.

Hope you enjoy the script and can find some use for it or its parts (like dealing with duplicates in multiple arrays, etc). You can never do enough matching ;)

Cheers,


Creative Commons License


This work is licensed under a
Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License

#!/usr/bin/perl

#
# match.pl - Updated to last longer and taste better :)
#
# 2008 - Mike Golvach - eggi@comcast.net
#
# Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License
#

use Getopt::Std;

%options = ();

# DIFF - Add -p option to pad 1-9
getopts("h:f:m:n:p", \%options);

if ( defined $options{m} && defined $options{h} && defined $options{f} && defined $options{n} ) {
$highnum = $options{h};
$combos = $options{n};
$statfile = $options{f};
$minmatch = $options{m};
if ( ! -f $statfile ) {
usage("File $options{f} Does Not Exist!");
} elsif ( $combos > 6 ) {
usage("Only Combos Up To 6 Please!");
}
} else {
usage("Invalid or incomplete options!");
}


open(FILE, "<$statfile");
@file = <FILE>;
close(FILE);

# DIFF - with -p, now have to differentiate
# DIFF - between straight and padded 1-9
for ( $lownum = 1; $lownum <= $highnum; $lownum++ ) {
if ( defined $options{p} && $lownum < 10 ) {
$padded_num = "0$lownum";
} else {
$padded_num = $lownum;
}
push(@numbers, "$padded_num");
}

# DIFF - Still not using a subroutine for this.
# Trying to stay away from arrays of array references, also
# for ease of understaning

@numbers1 = @numbers2 = @numbers3 = @numbers4 = @numbers5 = @numbers6 = "";
$one = $two = $three = $four = $five = $six = 1;
$start = 1;
while ( $start <= $combos ) {
if ( @numbers1 == 1 && $start == 1 ) {
@numbers1 = @numbers;
$one = 0;
} elsif ( @numbers2 == 1 && $start == 2 ) {
@numbers2 = @numbers;
$two = 0;
} elsif ( @numbers3 == 1 && $start == 3 ) {
@numbers3 = @numbers;
$three = 0;
} elsif ( @numbers4 == 1 && $start == 4 ) {
@numbers4 = @numbers;
$four = 0;
} elsif ( @numbers5 == 1 && $start == 5 ) {
@numbers5 = @numbers;
$five = 0;
} elsif ( @numbers6 == 1 && $start == 6 ) {
@numbers6 = @numbers;
$six = 0;
}
$start++;
}

foreach $cnum1 (@numbers1) {
foreach $cnum2 (@numbers2) {
foreach $cnum3 (@numbers3) {
foreach $cnum4 (@numbers4) {
foreach $cnum5 (@numbers5) {
foreach $cnum6 (@numbers6) {
@match = grep(/$cnum1/ && /$cnum2/ && /$cnum3/ && /$cnum4/ && /$cnum5/ && /$cnum6/, @file);
$match = @match;
if ( $match >= $minmatch ) {
undef %seen;
@success = grep(!$seen{$_}++, ($cnum1, $cnum2, $cnum3, $cnum4, $cnum5, $cnum6));
print "@success matches $match times:\n @match\n";
}
}
}
}
}
}
}

sub usage {
$message = shift;
print "Error Encountered! $message\n";
print "Usage: $0 -h highNumber -f statFile -n numberOfCombos -m mimimumCombos\n";
print "[-p padSingleDigitsWithZeros]\n";
exit(1);
}


, Mike




Please note that this blog accepts comments via email only. See our Mission And Policy Statement for further details.

Sunday, April 27, 2008

Perl Script To Translate Signal Names And Numbers

Hey There,

For this "Lazy Sunday" post I threw together a quick little Perl script to help out further with what we went over more thoroughly in our previous post on signal definitions in Linux and Unix.

This script takes at least one argument (or it throws a fit and refuses to cooperate with you ;) of either a signal name or signal number, which it will then translate to the other (does the way I wrote that make sense? ;)

So, if you want to know what signals 4 and 5 do, you could run:

host # ./siggy.pl 4 5
Signal Number 4 = ILL
Signal Number 5 = TRAP


And see the (somewhat more verbose) translations from the system includes. Conversely, you could want to know what numbers the TERM and KILL signals are, which you could get by running:

host # ./siggy.pl TERM KILL
Signal Name TERM = 15
Signal Name KILL = 9


Or you can mix and match. Do whatever, you want. If you throw the script an argument it doesn't understand it will react accordingly ;)

host # ./siggy.pl hup 8 ... 9
Signal Name HUP = 1
Signal Number 8 = FPE
...: What is that supposed to mean?
Signal Number 9 = KILL


One interesting thing in the script is the use of an absolute subroutine call. Even though I put the "use Sys::SigAction;" line in the script, Perl was interpreting the function calls (like sig_number()) as belonging to the Main:: module. Pretty much every function, or command, in Perl does. "print," for example, is actually Main::print, so I had to use "absolute" naming. Writing "Sys::SigAction::sig_number()" (in this instance) is one way to make sure that Perl knows exactly where to look for that subroutine to run :)

Cheers,


Creative Commons License


This work is licensed under a
Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License

#!/usr/bin/perl

#
# siggy.pl
#
# 2008 - Mike Golvach - eggi@comcast.net
#
# Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License
#

if ( $#ARGV < 0 ) {
print "Usage: $0 signalNumber1 [signalNumbern...]\n";
exit(1);
}

use Sys::SigAction;

@signos = @ARGV;

foreach $sig (@signos) {
if ( $sig =~ /[A-Za-z]+/ ) {
$sig = uc($sig);
$signum=Sys::SigAction::sig_number( $sig );
print "Signal Name $sig = $signum\n";
} elsif ($sig =~ /[0-9]+/) {
$signame=Sys::SigAction::sig_name( $sig );
print "Signal Number $sig = $signame\n";
} else {
print "$sig: What is that supposed to mean?\n";
}
}


, Mike

Tuesday, April 22, 2008

Functions Vs. Subroutines In Perl And Bash - Palindromes Revisited

Hey There,

As the clever title of today's post suggests, this is the follow up to our post on scripting out a way to determine if a string is a palindrome using Perl.

One of the main things to note (which isn't the only difference, of course) is the way in which the Bash shell and Perl deal differently with "routines." In our Perl script, we did the meat of our recursive work inside a "subroutine." In today's Bash script, that same work is handled inside a "function."

Functionally speaking, both a Perl "subroutine" (Identified by the "sub" declaration) and a Bash "function" (Identified by the "function" declaration) do the same things. They allow you to create a block of code for use within in your script. Naturally, functions and/or subroutines, are a great help if you find that your script consists of typing the same set of instructions more than once (if you have to type the same block of code more than twice, they're even better ;)

Technically speaking, there are some major differences between the two that should be noted. These should be platform independent and true for both Bash and Perl on Linux or Unix.

In Perl, since all of the information in the script is processed before the script is run, you can include your "subroutine" anywhere in the script, even if it's after the line on which you call it. It's common practice to put subroutines at the bottom of the script, but you can put them anywhere within the script that you like, if you're so inclined.

In Bash, since the script is parsed from top-to-bottom in a left-to-right fashion, "functions" absolutely need to appear in the script before the line on which they are called. If you put a function definition at the bottom of your Bash shell script and call that function 15 lines prior, you'll receive something along the order of a "command not found" error.

In Perl, when you pass arguments to a subroutine, you have a few different ways you can do it (basically, deprecated methods still work), but the most elegant way to pass simple variables to your Perl subroutine is to include them within parentheses, separated by commas, like so:

MySub( $var1, $var2, $var3);

The subroutine that would accept, and process, all of those arguments may look something like this:

sub MySub( $var1, $var2, $var3) {
print "$var1 $var2 $var3\n";
}


In Bash, when you pass arguments to a function, you can just pass them as if they were arguments to a regular command, like this:

MyFunction $var1 $var2 $var3

The function that would accept, and process, these arguments may look something like this:

function MyFunction {
echo "$var1 $var2 $var3"
}


Interesting side note: In Bash, if you declare a function, you can leave out the reserved word "function" if you want to, but this requires that you use parentheses, like with Perl. So you could write your function like this:

MyFunction () {
echo "$var1 $var2 $var3"
}


However, if you opt to use the reserved word "function" when declaring your function (like we do), the parentheses following the function name are optional :)

You may have noted that we haven't mentioned anything about "scope" with regards to variables and functions or subroutines. This is on purpose. We'll inevitably tackle that in a later post, but it's beyond the "scope" of this one (that was a truly painful pun for all of us... but utterly unavoidable ;)

On that note (for the palindromes), in our Bash script we've taken advantage of that "lack of scope" and simply set the "$status" variable globally within the palindrome function. In our Perl script, we used "return" to pass back either a 0 or a 1 to the calling procedure. The major difference here is that our Perl script was returning a code back to a variable which was defining its value based on the outcome of the subroutine process, so:

$status = palindrome( @string, $chars, $count );

was giving the "$status" variable a value of 0 or 1, depending on what the "palindrome" subroutine returned. In Bash, we jumped right over the middle man and just set the global "$status" variable from within the function (This isn't generally recommended, but okay for our purposes here). Assuming there are no bugs in your version of Bash that mangle the scope of variables within functions, the only risk you're taking, by defining a global variable from within a function, is that you'll forget about it and redefine it outside the function, thereby overwriting the value. But, again, that's for another day, as I can feel an essay coming on ;)

Hope you enjoy the Bash version of our simple palindrome script and that it helps you see the correlation between not only functions and subroutines, but some other aspects of coding that are either common, or unique, to both Bash and Perl.

Best wishes,

Cheers,


Creative Commons License


This work is licensed under a
Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License

#!/bin/bash

#
# bashpal.sh
#
# 2008 - Mike Golvach - eggi@comcast.net
#
# Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License
#

function palindrome {
if [ "${string:${count}:1}" == "${string:${chars}-${count}-1:1}" ]
then
let count=$count+1;
palindrome "$string" "$chars" "$count"
fi
if [ $count -eq $chars ]
then
status=1;
else
status=0;
fi
}

printf "Enter A String: "
read string

chars=${#string}
count=0
palindrome "$string" "$chars" "$count"

if [ $status -eq 1 ]
then
printf "\n That String Is A Palindrome.\n\n"
else
printf "\n That String Is Not A Palindrome.\n\n"
fi


, Mike




Sunday, April 20, 2008

Porting Perl To Shell Again - Palindromes

Hey There,

For this "Lazy Sunday" post, we're going to take a look at a Perl script, for Linux or Unix, that checks whether or not a string you input is a palindrome. As you probably know (but I feel I should explain anyway, just to be thorough ;), a palindrome is any set of letters, numbers, spaces, etc, that reads exactly the same forward or backward.

Check out this little script and notice the use of recursion to both maintain a pseudo "state" and the use of a single subroutine to perform what could be a complex operation.

We'll port this to shell in a few days (like we've done in our post on porting a web element reporting script and its improved log checking follow up), with more explanation of what's going on, and the why and how of what gets changed when we port from Perl to shell.

Enjoy your Sunday and relax :)

Cheers,


Creative Commons License


This work is licensed under a
Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License

#!/usr/bin/perl

#
# perlpal.sh
#
# 2008 - Mike Golvach - eggi@comcast.net
#
# Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License
#

print "Enter A String: ";
$string=<STDIN>;
chomp($string);

$chars = length($string);
@string = split(//, $string);
$count=0;
$status = palindrome( @string, $chars, $count );


if ( $status == 1 ) {
print "\n That String Is A Palindrome.\n\n";
} else {
print "\n That String Is Not A Palindrome.\n\n";
}

sub palindrome(@string, $n\chars, $count) {
if ( $string[$count] eq $string[$chars-$count-1] ) {
$count++;
palindrome($string, $chars, $count);
}
if ($count == $chars) {
return 1;
} else {
return 0;
}
}


, Mike