Weblog maken?


MaakEenWebsite.nl (tip)
Totaal slechts 10 euro per maand incl. domeinnaam en gratis overzetten van uw bestaande weblog bij Bloggers.nl 100 MB ruimte
emailadres
Lees meer..... en bestel
Gratis geld verdienen met e-mails lezen? Meld je aan bij
Zinngeld, Surfrace, Qassa en Euroclix !

Op zoek naar God?
trekhaak Home | Profile | Archives | Friends
perl routines of stukjes code

# eigen naam script7/2/2006
soms is het prettig om de eigen naam van het script te weten omdat het script van naam veranderd kan zijn.

Deze naam is opgeslagen in de speciale variabele $0


1 Comments | Post Comment | Permanent Link

# emailen6/2/2006
  open(MAIL,"|/usr/sbin/sendmail -t");
  print MAIL "To: gadele\@host.nl\n";
  print MAIL "From: kniert\@host.nl\n";
  print MAIL "Cc: kniert2\@host.nl\n";
  print MAIL "Subject: onderwerp\n\n";
  print MAIL "$data";
  close(MAIL);

0 Comments | Post Comment | Permanent Link

# links naar goede perl docs7/1/2006
speciale variabelen - http://www.perl.com/lpt/a/2004/06/18/variables.html

perl 5 reference guide - http://www.rexswain.com/perl5.html

perl 5 by example - http://affy.blogspot.com/p5be/

perl scalar operators en regular expressions - http://www.kichwa.com/quik_ref/



0 Comments | Post Comment | Permanent Link

# speciale variabelen7/1/2006
Variables That Affect Arrays
$"     The separator used between list elements when an array variable is interpolated into a double-quoted string. Normally, its value is a space character.
$[     Holds the base array index. Normally, set to 0. Most Perl authors recommend against changing it without a very good reason.
$;     Holds the subscript separator for multi-dimensional array emulation.

Variables Used with Files
$.         This variable holds the current record or line number of the file handle last read. It is read-only and will be reset to 0 when the file handle is closed.
$/         This variable holds the input record separator. The record separator is usually the newline character. However, if $/ is set to an empty string, two or more newlines in the input file will be treated as one.
$|         This variable, if nonzero, will flush the output buffer after every write() or print() function. Normally, it is set to 0.
$^F     This variable holds the value of the maximum system file description. Normally, it's set to 2. The use of this variable is beyond the scope of this book.
$ARGV     This variable holds the name of the current file being read when using the diamond operator (<>).
_         This file handle (the underscore) can be used when testing files. If used, the information about the last file tested will be used to evaluate the latest test.
DATA         This file handle refers to any data following __END__.
STDERR     This file handle is used to send output to the standard error file. Normally, this is connected to the display, but it can be redirected if needed.
STDIN         This file handle is used to read input from the standard input file. Normally, this is connected to the keyboard, but it can be changed.
STDOUT     This file handle is used to send output to the standard output file. Normally, this is the display, but it can be changed.

Variables Used with Patterns
$&     This variable holds the string that was matched by the last successful pattern match.
$`     This variable holds the string that preceded whatever was matched by the last successful pattern match.
$'     This variable holds the string that followed whatever was matched by the last successful pattern match.
$+     This variable holds the string matched by the last bracket in the last successful pattern match. For example, the statement /Fieldname: (.*)|Fldname: (.*)/ && ($fName = $+); will find the name of a field even if you don't know which of the two possible spellings will be used.
$*     This variable changes the interpretation of the ^ and $ pattern anchors. Setting $* to 1 is the same as using the /m option with the regular expression matching and substitution operators. Normally, $* is equal to 0.
$     This group of variables ($1, $2, $3, and so on) holds the regular expression pattern memory. Each set of parentheses in a pattern stores the string that matches the components surrounded by the parentheses into one of the $ variables.

Variables Used with Printing
$,     This variable is the output separator for the print() function. Normally, this variable is an empty string. However, setting $, to a newline might be useful if you need to print each element in the parameter list on a separate line.
$\     The variable is added as an invisible last element to the parameter list passed to the print() function. Normally, it's an empty string, but if you want to add a newline or some other suffix to everything that is printed, you can assign the suffix to $\.
$#     This variable is the default format for printed numbers. Normally, it's set to %.20g, but you can use the format specifiers covered in by the section "Example: Printing Revisited" in Chapter 9 to specify your own default format.

Variables Used with Processes
$$     This UNIX-based variable holds the process number of the process running the Perl interpreter.
$?     This variable holds the status of the last pipe close, back-quote string, or system() function. More information about the $? variable can be found in Chapter 13, "Handling Exceptions and Signals."
$0     This variable holds the name of the file containing the Perl script being executed.
$]     This variable holds a string that identifies which version of Perl you are using. When used in a numeric context, it will be equal to the version number plus the patch level divided by 1000.
$!     This variable, when used in a numeric context, holds the current value of errno. If used in a string context, it will hold the error string associated with errno. For more information about errno, see Chapter 13, "Handling Exceptions and Signals."
$@     This variable holds the syntax error message, if any, from the last eval() function call. For more information about errno, see Chapter 13, "Handling Exceptions and Signals."
$<     This UNIX-based variable holds the read uid of the current process.
$>     This UNIX-based variable holds the effective uid of the current process.
$)     This UNIX-based variable holds the read gid of the current process. If the process belongs to multiple groups, then $) will hold a string consisting of the group names separated by spaces.
$^T     This variable holds the time, in seconds, at which the script begins running.
$^X     This variable holds the full path name of the Perl interpreter being used to run the current script.
%ENV     This hash variable contains entries for your current environment variables. Changing or adding an entry will affect only the current process or a child process, never the parent process. See the section "Example: Using the %ENV Variable" later in this chapter.
%SIG     This hash variable contains entries for signal handlers. For more information about signal handlers, see Chapter 13, "Handling Exceptions and Signals."

Variables Used with Reports
$%     This variable holds the current page number for the default file handle. If you use select() to change the default file handle, $% will change to reflect the page number of the newly selected file handle.
$=     This variable holds the current page length for the default file handle. Changing the default file handle will change $= to reflect the page length of the new file handle.
$-     This variable holds the number of lines left to print for the default file handle. Changing the default file handle will change $- to reflect the number of lines left to print for the new file handle.
$~     This variable holds the name of the default line format for the default file handle. Normally, it is equal to the file handle's name.
$^     This variable holds the name of the default heading format for the default file handle. Normally, it is equal to the file handle's name with _TOP appended to it.
$:     This variable holds a string that consists of the characters that can be used to end a word when word-wrapping is performed by the ^ report formatting character. Normally, the string consists of the space, newline, and dash characters.
$^L     This variable holds the string used to eject a page for report printing. Chapter 11, "Creating Reports," shows how to use this variable to create simple footers.

Miscellaneous Variables
$_     This variable is used as the default parameter for a lot of functions.
$^D     This variable holds the current value of the debugging flags. For more information, see Chapter 16, "Debugging Perl."
$^I     This variable holds the file extension used to create a backup file for the in-place editing specified by the -i command line option. For example, it could be equal to ".bak."
$^P     This variable is an internal flag that the debugger clears so that it will not debug itself.
$^W     This variable holds the current value of the -w command line option.
@ARGV     This array variable holds a list of the command line arguments. You can use $#ARGV to determine the number of arguments minus one.
@F     This array variable holds the list returned from autosplit mode. Autosplit mode is associated with the -a command line option.
@INC     This array variable holds a list of directories where Perl can look for scripts to execute. The list is used mainly by the require statement. You can find more information about require statements in Chapter 15, "Perl Modules."
%INC     This hash variable has entries for each filename included by do or require statements. The key of the hash entries are the filenames and the values are the paths where the files were found.


(Posted in perl)
0 Comments | Post Comment | Permanent Link

# flip-flop operator (van tot)7/1/2006
One other nice way to use $. is in conjunction with Perl's "flip-flop" operator (..). When used in list context, .. is the list construction operator. It builds a list of elements by calculating all of the items between given start and end values like this:

  my @numbers = (1 .. 1000);

But when you use this operator in a scalar context (like, for example, as the condition of an if statement), its behavior changes completely. The first operand (the left-hand expression) is evaluated to see if it is true or false. If it is false then the operator returns false and nothing happens. If it is true, however, the operator returns true and continues to return true on subsequent calls until the second operand (the right-hand expression) returns true.

An example will hopefully make this clearer. Suppose you have a file and you only want to process certain sections of it. The sections that you want to print are clearly marked with the string "!! START !!" at the start and "!! END !!" at the end. Using the flip-flop operator you can write code like this:

  while () {
    if (/!! START !!/ .. /!! END !!/) {
      # process line
    }
  }

Each time around the loop, the current line is checked by the flip-flop operator. If the line doesn't match /!! START !!/ then the operator returns false and the loop continues. When we reach the first line that matches /!! START !!/ then the flip-flop operator returns true and the code in the if block is executed. On subsequent iterations of the while loop, the flip-flop operator checks for matches again /!! END !!/, but it continues to return true until it finds a match. This means that all of the lines between the "!! START !!" and "!! END !!" markers are processed. When a line matches /!! END !!/ then the flip-flop operator returns false and starts checking against the first regex again.

So what does all this have to do with $.? Well, there's another piece of magic coded into the flip-flop operator. If either of its operands are constant values then they are converted to integers and matched against $.. So to print out just the first 10 lines of a file you can write code like this:

  while () {
    print if 1 .. 10;
  }
 
  


(Posted in perl)
0 Comments | Post Comment | Permanent Link

# subroutines7/1/2006
subroutines mogen overal in de code voorkomen dus zowel voor als na de aanroep ervan. In onderstaand voorbeeld wordt de routine eerst aangeroepen en later pas staat de code. Aanroepen van een subroutine gebeurt dus door een & ervoor te zetten en maken van een subroutine door een willekeurige routine met accoladehaken af te zetten en de routine een naam te geven "sub xxx {xxx}"

&doiets;

sub doiets {
  #uitvoer subroutine;
}


Soms is het praktisch om variabelen niet globaal te gebruiken maar mee te geven aan de subroutine zoals bijvoorbeeld in het volgende voorbeeld waarbij er dus met $var iets gebeurt in de routine.

$var=1;
&subr;
$var=2;
&subr;
$var=3;
&subr;

Beter zou zijn:

&subr(1);
&subr(2);
&subr(3);

Een loop kan uiteraard ook.

Parameters meegeven aan subroutines is geen probleem, zie het volgende voorbeeld.

sub doiets{
  $tekst=$_[0];
  $getal=$_[1];
}

&doiets("hallo",10);



(Posted in perl)
0 Comments | Post Comment | Permanent Link

# hash loops23/12/2005

while(($key, $value) = each(%HASH)) {
# do something with $key and $value
}

Of met het commando keys in een foreach loop, unless the hash is potentially very large:

foreach $key (keys %HASH) {
$value = $HASH{$key};
# do something with $key and $value
}
Waarom weet ik niet maar de inhoud van de hash zal door elkaar retour komen behalve als er een sort meegegeven wordt in de loop

foreach $key (sort keys %HASH) {
    $value = $HASH{$key};
# do something with $key and $value
}
0 Comments | Post Comment | Permanent Link

# datum en tijd23/12/2005
Met het localtime(time) commando is de datum en tijd af te lezen in afzonderlijke velden

  ( $sec, $min, $hour, $day, $mon, $year, $wday, $yday, $isdst ) = localtime( time );

Wanneer in bovenstaand voorbeeld niet alle velden gebruikt worden dan zal het script een foutmelding geven dat de variabele maar één keer gebruikt is. Dit is op te lossen door die variabelen ook nog eens te initializeren (nul waarde geven) maar ook door maar enkele velden te kiezen zoals te zien in onderstaand voorbeeld.

  ( $day, $mon, $year ) = ( localtime(time) )[ 3, 4, 5 ];

Datum format netjes weergeven met printf voor het opvullen van de waarden met nullen:

  ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time);
  printf "%4d-%02d-%02d %02d:%02d:%02d\n",$year+1900,$mon+1,$mday,$hour,$min,$sec;

  # perl time.pl
  2003-02-14 16:37:46

zoals te zien is begint de maandtelling bij 0 dus moet er één bij opgeteld worden. De jaartelling begint bij 1900 dus moet er 1900 bij opgeteld worden.

(Posted in perl)
0 Comments | Post Comment | Permanent Link

# controleer en converteer mac adressen11/12/2005
#!/usr/bin/perl
# converteer mac adressen tussen dubbele punt format (o.a. cisco IOS) en
# dotted format (Cisco set based)

$mac="00:01:02:03:04:05";


  if ($mac =~ /[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}/ ) {
    #dubbele punt format, genereer dotted format;
    print "dubbele punt format\n";
    $macdot=substr($mac,0,2).substr($mac,3,2).".".substr($mac,6,2).substr($mac,9,2).".".substr($mac,12,2).substr($mac,15,2);
    print "$mac --> $macdot\n";
  }


$mac="0001.0203.0405";

  if ($mac =~ /[0-9a-fA-F]{4}.[0-9a-fA-F]{4}.[0-9a-fA-F]{4}/) {
    #dotted format, genereer dubbele punt format;
    print "dotted format\n";
    $macdp=substr($mac,0,2).":".substr($mac,2,2).":".substr($mac,5,2).":".substr($mac,7,2).":".substr($mac,10,2).":".substr($mac,12,2);
    print "$mac --> $macdp\n";
  }


(Posted in perl)
0 Comments | Post Comment | Permanent Link

# tekst formatting in file10/12/2005
Tekst formatting naar een file kan met printf maar ook volgens een format

   write (RESULTS);

Geeft een format aan. RESULTS is de filehandle van de outputfile.

   format RESULTS =
   @<<<<<<<<<<<<<<< @>>
   $w,              $count{$w}
   .

eerste regel:
@=variabele,
<<<<<<=links uitlijnen en veldlengte is aantal kleiner dan tekens,

>>>=rechts uitlijnen met veldlengte drie.
Een optie is ook:
@||||=centreren in veldlengte vier

De tweede regel zijn de velden/variabelen (spaties niet nodig maar cosmetisch)
Op de laatste regel staan alleen een punt !!!

Tot slot kan ook een header gedefinieerd worden (als eerste dan wel)

   format RESULTS_TOP =
   Word         Frequency      (Page @)
                                               $%
   .

Let weer op de punt op de derde regel. Spaties voor de variabele zijn wederom cosmetisch.


(Posted in perl)
0 Comments | Post Comment | Permanent Link

# chop en chomp10/12/2005
Beide commando's lijken op elkaar. chop haalt het laatste character van een string af en chomp doet dat alleen als dit character een newline character is.

chomp kan gebruikt worden als er bijvoorbeeld een string ingegeven is of ingelezen uit een file. Deze string bevat dan ook de enter aan het einde van de regel terwijl deze ongewenst is.


  chomp($string);



(Posted in perl)
0 Comments | Post Comment | Permanent Link

# reguliere expressies en meta characters10/12/2005
# reguliere expressies

  [0-9]        matches any single digit
  [0-9]+       matches any sequence of one or more digits
  [a-z]+       matches any lowercase word 
  /at/         matches "at", "attention", "flat", & "flatter"
# ^ is begin, $ is einde
  /^at/        matches "at" & "attention" but not "flat"
  /at$/        matches "at" & "flat", but not "attention"
  /^at$/       matches "at" and nothing else.
  /^at$/i      matches "at", "At", "aT", and "AT". 
# speciale characters moeten een backslash hebben om gezien te worden
# een . betekent elk character
  /10.2/       matches "10Q2", "1052", and "10.2"
  /10.2/      matches "10.2" but not "10Q2" or "1052"

metacharacters voor in de regulair expressions

+ één of meer characters
* nul of meer charcters
? één of nul characters
$ aan het einde
^ aan het begin
. één character

slash-W geen woord
slash-w elk woord, inclusief underscore en digits
slash-s spatie/tab/return
slash-S non spatie
slash-t tab
slash-d decimaal getal
slash-D niet decimaal
slash-f form feed character
slash-n newline character
slash-r return character
xHEX 1 of 2 hex digits ()
x{hex} langere hex waarde (FA)
l          lowercase next char (think vi)
u          uppercase next char (think vi)
L          lowercase till E (think vi)
U          uppercase till E (think vi)
E          end case modification (think vi)
Q          quote (disable) pattern metacharacters till E


  /p+/         meerdere p's
  /p{2}/       twee p's (pp)
  /[0-9]/      een getal
  /[0-9]{2}/   een getal bestaande uit twee digits
  /[0-9]{2,}/  een getal bestaande uit minimaal 2 digits
  /[0-9]{2,4}/ een getal bestaande uit 2,3 of 4 digits
  /e(r|st)/    er of est
  /(ti)+/      één of meer keren "ti"
  /^SW/        "SW" aan het begin van de string
  /SW$/        "SW" aan het einde van de string

# Test of variabele een geldig mac adres is in dubbele punt formaat (boven) en dotted format
$mac =~ /[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}/
$mac =~ /[0-9a-fA-F]{4}.[0-9a-fA-F]{$}.[0-9a-fA-F]{4}/


(Posted in perl)
0 Comments | Post Comment | Permanent Link

# split10/12/2005
Met split kan een string opgedeeld worden in meerdere strings waarbij het eerste argument het scheidingsteken aangeeft. Een scheidingsteken kan een spatie of een dubbele punt zijn.
split zonder argumenten geeft aan dat $_ de string is en een spatie het scheidingsteken

  split;

Een mooie oplossing is:

  @newstring = split(/s+/,$string);
 
Hierbij staat het scheidingsteken tussen slashes wat aangeeft dat het een reguliere expressie is en in dit geval betekent het één of meerdere (+) spaties maar ook een tab of enter. Ideaal dus voor vage kolom scheidingen in de input.

 ($uid,$pid,$ppid,$restOfLine) = split;


output van ps opdelen in variabelen


(Posted in perl)
0 Comments | Post Comment | Permanent Link

# parameters9/12/2005
# aantal parameters  
  $numArgs = $#ARGV + 1;      # telling begint bij 0

# doe iets met args
  for($i = 0; $i < @ARGV; ++$i){
      print($ARGV[$i]." ");
  }  


foreach $argnum (0 .. $#ARGV) {
  print "$ARGV[$argnum]\n";
}

(Posted in perl)
0 Comments | Post Comment | Permanent Link

# Converteer decimaal naar hex9/12/2005
  $hex=sprintf("%X",$dec);


(Posted in perl)
0 Comments | Post Comment | Permanent Link

# test filesize9/12/2005
# Filesize testen
  $filesize = -s "test.txt";
  print "Size: $filesize\n";


(Posted in perl)
0 Comments | Post Comment | Permanent Link

# are you root9/12/2005
# Are you r00t?
  if($> != 0)
  {
    die "You need EUID 0 to use this tool!\n\n";
  }


(Posted in perl)
0 Comments | Post Comment | Permanent Link

# endless loops9/12/2005
  while ( 1 )                       # always true
  {   
    # aktie;
  }  



# endless loop met for
  for (;;) { doiets }

(Posted in perl)
0 Comments | Post Comment | Permanent Link

# Loop 10x uitvoeren9/12/2005
  for ( $i = 1; $i <= 10; $i++)
  {
    # aktie die tien keer wordt uitgevoerd
  } 


(Posted in perl)
0 Comments | Post Comment | Permanent Link

# controleren of een gestart script al loopt en zo niet dan verder uitvoeren9/12/2005
# $$ is PID van eigen process, de laatste grep is om het grep commando zelf
# niet mee te tellen.    
  $run=`ps ax | grep names.p | grep -v "$$" | grep -v "grep names.p"`;
  if ( $run eq "" ) {
    #runnen als er geen proces al loopt...
  } 


(Posted in perl)
0 Comments | Post Comment | Permanent Link

# array opslaan in variabelen9/12/2005
  ($infile,$outfile) = @ARGV;    
  ($stuid,$name,$year) = split(':',$_);
# split zonder parameters gaat uit van $_ en spatie als scheiding
  ($stuid,$examno,$score) = split;


(Posted in perl)
0 Comments | Post Comment | Permanent Link

# test of file bestaat9/12/2005
# uitroepteken is ontkenning  
  if (! -r $infile) {
    die "Can't read input $infile\n";
  }
  if (! -f $infile) {
    die "Input $infile is not a plain file\n";
  }  
  if ( -e $outfile) {
    print "Output file $outfile exists!\n";


(Posted in perl)
0 Comments | Post Comment | Permanent Link

# convert to lowercase with tr (translate)9/12/2005
  $foo =~ tr /A-Z/a-z/; 


(Posted in perl)
0 Comments | Post Comment | Permanent Link

# substitue9/12/2005
# wijzig patern in patern2 (substitute)  
  $variable =~ s/pattern/pattern2/
# wijzig $_
  s/pattern/pattern2/   
# hieronder zijn de slashes vervangen door vraagtekens voor de leesbaarheid
# dit mag dus. $1 is de waarde van de match tussen de haakjes, het nummer dus.
# deze regel vervangt regels in de format U+53728 in U+53728
  s?U\+([0-9a-fA-F]+)?U\+$1?g;  


(Posted in perl)
0 Comments | Post Comment | Permanent Link

# file opslaan in hash9/12/2005
# file opslaan in hash   
  open(F,"switches.dat");
  while() {
    @aa=split(' ',$_);
    $ha{$aa[0]}=$aa[1];
  }
  close(F);
  print "$ha{SW01} $ha{SW04} ";


(Posted in perl)
0 Comments | Post Comment | Permanent Link

# argumenten opdelen en opslaan in hash9/12/2005
  for($i = 0; $i < @ARGV; ++$i){
    if ($ARGV[$i] =~ "^-") {
      $ha{$ARGV[$i]}=$ARGV[$i+1];
      print "$ARGV[$i] $ha{$ARGV[$i]} ";
    }
  }

#output
  perl parms.p -f hallo -r hallo2
  -f hallo
  -r hallo2


(Posted in perl)
0 Comments | Post Comment | Permanent Link

# voer commando gecontroleerd uit9/12/2005
#!/usr/bin/perl
open (PINGTEST, "/bin/ping -c 5 netadmintools.com |");
$i=1;
while (){
print "Line # ".$i." ".$_;
$i++;
}
print "All done!\n";
close PINGTEST;


if (! open (DUPIPE,"du -sk $files | sort -nr |"))  {
  die "Can't run du! $! ";
}
while () {
  # parse the du info:
  ($kbytes, $filename) = split;
}
close(DUPIPE);



(Posted in perl)
0 Comments | Post Comment | Permanent Link
Hosting door HQ ICT Systeembeheer