Durch Nutzung dieser Webseite stimmen Sie dem Einsatz von Cookies und Werbung zu. Weitere Informationen



KnowHow 8.13 ''Perl ''
Stand: 31.07.2017 16:42:00

Inhalt | Suche | Homepage | Kontakt | Impressum

- Durch Anklicken im Inhaltsverzeichnis kann direkt zum Thema gesprungen werden.
- Begriffe auf dieser Seite können mit Ihrer Browser-Funktion ''Bearbeiten -> Suchen'' oder mit den Tasten [Strg]-[F] gesucht werden.
- Des weiteren gibt es noch eine Suchfunktion über alles.
- Es sind mehr Informationen verfügbar, als hier angegeben. Falls Sie etwas vermissen, scheuen Sie sich nicht nachzufragen, wir antworten gerne.




8.13.1 Perl unter Linux

Linux hat standardmäßig Perl installiert
Hier müssen zusätzliche Pakete von Hand installiert werden

Es kann auch das kostenlose Active Perl installiert werden
http://www.activestate.com/activeperl
http://www.chip.de/downloads/ActivePerl-fuer-Linux-_-Mac-OS_12992133.html
Hier ist der komfortable Perl Package Manager (PPM) integriert

Beim Installieren der ActivePerl Community Edition Version 5.16.3.1604 für Linux (X86)
http://downloads.activestate.com/ActivePerl/releases/5.16.3.1604/ActivePerl-5.16.3.1604-i686-linux-glibc-2.3.6-298023.tar.gz
tritt folgender Fehler auf:
Checking package...
- file 'perl/man/man1/c2ph.1' corrupt.
- file 'perl/man/man1/perlbug.1' corrupt.
- file 'perl/man/man1/psed.1' corrupt.
This installer package does not have the expected content.  Please
try to download a fresh copy of ActivePerl from ActiveState's website
at <http://www.activestate.com>.  If you still have problems please
contact us at <support@activestate.com>.



8.13.1.1 Zusätzliche Perl-Module installieren (1)

Quelle: http://www.livejournal.com/doc/server/lj.install.perl_setup.modules.html

Notwendige Perl-Module:

DateTime           libdatetime-perl
DBI                libdbi-perl
DBD::mysql         libdbd-mysql-perl
Class::Autouse     libclass-autouse-perl
Digest::MD5        libmd5-perl
Digest::SHA1       libdigest-sha1-perl
HTML::Template     libhtml-template-perl
Image::Size        libimage-size-perl
MIME::Lite         libmime-lite-perl
MIME::Words        libmime-perl
Compress::Zlib     libcompress-zlib-perl
Net::DNS           libnet-dns-perl
URI::URL           liburi-perl
HTML::Tagset       libhtml-tagset-perl
HTML::Parser       libhtml-parser-perl
LWP::Simple        libwww-perl
LWP::UserAgent     libwww-perl
GD                 libgd-gd2-perl
Mail::Address      libmailtools-perl
Unicode::MapUTF8   libunicode-maputf8-perl
XML::Simple        libxml-simple-perl
IO::WrapTie        libio-stringy-perl
Unicode::CheckUTF8 ?
Captcha::reCAPTCHA libcaptcha-recaptcha-perl
Digest::HMAC_SHA1  libdigest-hmac-perl

Optional Module:

GD::Graph, libgd-graph-perl
    Required for making graphs for the statistics page.
Proc::ProcessTable, libproc-process-perl
    Better reliability for starting daemons necessary for high-traffic installations.
RPC::XML, librpc-xml-perl
    Required for outgoing XML-RPC support
SOAP::Lite, libsoap-lite-perl
    Required for XML-RPC support.
XML::RSS, libxml-rss-perl
    Required for retrieving RSS off of other sites (syndication).
String::CRC32, libstring-crc32-perl
    Required for palette-altering of PNG files. Only necessary if you plan to make your own S2 styles that use PNGs, not GIFs.
XML::Atom, libxml-atom-perl
    Required for Atom API support.
Math::BigInt::GMP, libmath-bigint-gmp-perl
    Aides Crypt::DH so it is not crazy slow.
URI::Fetch, liburi-fetch-perl
    Required for OpenID support.
Crypt::DH, libcrypt-dh-perl
    Required for OpenID support.
Image::Magick, perlmagick
    Required for the userpic factory.
Class::Accessor, libclass-accessor-perl
    Required for TheSchwartz job submission.
Class::Trigger, libclass-trigger-perl
    Required for TheSchwartz job submission.
Class::Data::Inheritable, libclass-data-inheritable-perl
    Required for TheSchwartz job submission.
GnuPG::Interface, libgnupg-interface-perl
    Required for email posting.
Mail::GnuPG, libmail-gnupg-perl
    Required for email posting.
Text::vCard, libtext-vcard-perl
    Used to generate user vCards.
IP::Country::Fast,
    Required for country lookup with IP address.
GTop,
    Required for Apache per-request database logging.


Installation mit DEBIAN:

su
apt-get install libdatetime-perl
apt-get install libdbi-perl
apt-get install libdbd-mysql-perl
apt-get install libclass-autouse-perl
apt-get install libmd5-perl
apt-get install libdigest-sha1-perl
apt-get install libhtml-template-perl
apt-get install libimage-size-perl
apt-get install libmime-lite-perl
apt-get install libmime-perl
apt-get install libcompress-zlib-perl
apt-get install libnet-dns-perl
apt-get install liburi-perl
apt-get install libhtml-tagset-perl
apt-get install libhtml-parser-perl
apt-get install libwww-perl
apt-get install libgd-gd2-perl
apt-get install libmailtools-perl
apt-get install libunicode-maputf8-perl
apt-get install libxml-simple-perl
apt-get install libio-stringy-perl
apt-get install libcaptcha-recaptcha-perl
apt-get install libdigest-hmac-perl
Optionale Module:
su
apt-get install libgd-graph-perl
apt-get install libproc-process-perl
apt-get install librpc-xml-perl
apt-get install libsoap-lite-perl
apt-get install libxml-rss-perl
apt-get install libstring-crc32-perl
apt-get install libxml-atom-perl
apt-get install libmath-bigint-gmp-perl
apt-get install liburi-fetch-perl
apt-get install libcrypt-dh-perl
apt-get install perlmagick
apt-get install libclass-accessor-perl
apt-get install libclass-trigger-perl
apt-get install libclass-data-inheritable-perl
apt-get install libgnupg-interface-perl
apt-get install libmail-gnupg-perl
apt-get install libtext-vcard-perl


Installation mit CPAN:

Start CPAN Shell:
sudo perl -MCPAN -e shell

Upgrade CPAN:
cpan> install Bundle::CPAN

Reload:
cpan> reload cpan

Einzelne Module installieren:
cpan> install DateTime
cpan> install DBI
cpan> install DBD::mysql
cpan> install Class::Autouse
cpan> install Digest::MD5
cpan> install Digest::SHA1
cpan> install HTML::Template
cpan> install Image::Size
cpan> install MIME::Lite
cpan> install MIME::Words
cpan> install Compress::Zlib
cpan> install Net::DNS
cpan> install URI::URL
cpan> install HTML::Tagset
cpan> install HTML::Parser
cpan> install LWP::Simple
cpan> install LWP::UserAgent
cpan> install GD
cpan> install Mail::Address
cpan> install Unicode::MapUTF8
cpan> install XML::Simple
cpan> install IO::WrapTie
cpan> install Unicode::CheckUTF8
cpan> install Captcha::reCAPTCHA
cpan> install Digest::HMAC_SHA1
cpan> install Net::SFTP

Optionale Module:
cpan> install GD::Graph
cpan> install Proc::ProcessTable
cpan> install RPC::XML
cpan> install SOAP::Lite
cpan> install XML::RSS
cpan> install String::CRC32
cpan> install XML::Atom
cpan> install Math::BigInt::GMP
cpan> install URI::Fetch
cpan> install Crypt::DH
cpan> install Image::Magick
cpan> install Class::Accessor
cpan> install Class::Trigger
cpan> install Class::Data::Inheritable
cpan> install GnuPG::Interface
cpan> install Mail::GnuPG
cpan> install Text::vCard
cpan> install IP::Country::Fast
cpan> install GTop


Problem: "Warning: Your /home/bur/.cpan/sources/modules/02packages.details.txt.gz does not contain a Last-Updated header."
evtl. zerstörte Dateien:
Lösung:
/home/bur/.cpan umbennenen oder löschen
sudo perl -MCPAN -e shell
-> neue Installation von cpan beginnt





8.13.1.2 Perl Modul für Email

In der CPAN Shell die Bibliothek Net::SMTP::SSL installieren:
sudo perl -MCPAN -e shell
cpan> install Net::SMTP::SSL
cpan> bye

Aufruf im Perl-Skript:
use Net::SMTP::SSL;



8.13.1.3 FTP

Bei ist ab 15.06.2016 der Datentransfer mit FTP nicht mehr erlaubt, jetzt nur noch mit SFTP und RSSH
Dafür das SFTP installieren:
sudo perl -MCPAN -e shell
cpan> install Net::SFTP
cpan> bye


Problem bei Installation

Lösung: "Net::SFTP::Foreign" verwenden
http://www.perlmonks.org/?node_id=532173
http://search.cpan.org/~salva/Net-SFTP-Foreign-1.86/lib/Net/SFTP/Foreign.pm
http://www.perlmonks.org/?node_id=668608

sudo perl -MCPAN -e shell
cpan> install Net::SFTP::Foreign
cpan> bye


Im RaspberryPi ist noch folgendes nötig:
cpan> install IO::Pty
Trotzdem Probleme im RaspberryPi:
"authenticity of the target host can't be established, the remote host public key is probably not oresent on the '~/.ssh/known_hosts' file ..."

Lösung:
-> siehe auch SSH Key

+-----------------+

sftp <user>@www.burgermeisters.de
<user>@www.burgermeisters.de's password: ...
Connected to www.burgermeisters.de.
sftp> ...
ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/pi/.ssh/id_rsa):
Enter passphrase (empty for no passphrase): ...
Enter same passphrase again: ...
Your identification has been saved in /home/pi/.ssh/id_rsa.
Your public key has been saved in /home/pi/.ssh/id_rsa.pub.
The key fingerprint is:
xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx pi@raspberrypi
The key's randomart image is:
+--[ RSA 2048]----+
. ..bo
o+oo..
. *ox o
o *..
S..
.A+
=o.
+ o
. o


Anwendungs-Beispiel mit Net::SFTP::Foreign:
sub upload_file { local($filenam,$ftpdestdir)=@_;
  use Net::SFTP::Foreign;
  my $ftp;
  my $ftphost = "www.burgermeisters.de";
  my $ftpuser = "...";
  my $ftppass = "...";
  my $errors; # ???
  $ftp = Net::SFTP::Foreign->new($ftphost, user => $ftpuser, password => $ftppass) or die "new failed!" . $ftp->error;
  $ftp->mkdir("$ftpdestdir"); or die "setcwd failed!" . $ftp->error;
  $ftp->setcwd("$ftpdestdir") or die "setcwd failed!" . $ftp->error;
  $ftp->put("$filenam", "$filenam", copy_perm => 0 ) or die "put failed!" . $ftp->error;
  $ftp->disconnect or die "disconnect failed!" . $ftp->error;
}



Problem: Bei put und mkdir werden die Rechte der Dateien mit übernommen und müssen extra gesetzt werden

Lösung:
$sftp->put($local, $remote, %opts)
  Uploads a file $local from the local host to the remote host saving it as $remote. By default file attributes are also copied.
  %opts:
    copy_perm => $bool    ( z.B. $sftp->put($local, $remote, copy_perm => 0) )
      determines if permission attributes have to be copied from remote file. Default is to copy them after applying the local process umask.
    perm => $perm         ( z.B. $sftp->put($local, $remote, perm => 0755) )
      sets the permission mask of the file to be $perm, umask and local permissions are ignored.
$sftp->mkdir($path, $attrs)
    Sends a SSH_FXP_MKDIR command to create a remote directory $path whose attributes are initialized to $attrs (a Net::SFTP::Foreign::Attributes object).
    Returns a true value on success and undef on failure.
    The $attrs argument is optional.


Problem:
WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
Someone could be eavesdropping on you right now (man-in-the-middle attack)!
It is also possible that a host key has just been changed.
The fingerprint for the DSA key sent by the remote host is
xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx.
Please contact your system administrator.
Add correct host key in /home/pi/.ssh/known_hosts to get rid of this message.
Offending DSA key in /home/pi/.ssh/known_hosts:2
DSA host key for www.burgermeisters.de has changed and you have requested strict checking.
Host key verification failed.
setcwd failed!SSH slave exited unexpectedly with error code 255 at test.pl line 367.

Lösungen:
http://serverfault.com/questions/6233/how-to-remove-strict-rsa-key-checking-in-ssh-and-whats-the-problem-here
sed -i 377d ~/.ssh/known_hosts
oder:
remove StrictHostKeyChecking, when you only need to do it for a single server:
ssh <server> -o StrictHostKeyChecking=no



############################
Eigene Lösung, funktioniert:

Muss scheinbar jede Woche wiederholt werden:

mv ~/.ssh/known_hosts ~/.ssh/known_hosts_bak
mv ~/.ssh/id_rsa ~/.ssh/id_rsa_bak
ssh-keygen -t rsa -N <new_passphrase> -f ~/.ssh/id_rsa
sftp <username>@www.burgermeisters.de
  The authenticity of host 'www.burgermeisters.de (xxx.xxx.xxx.xxx)' can't be established.
  ECDSA key fingerprint is xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx.
  Are you sure you want to continue connecting (yes/no)? yes
  Warning: Permanently added 'www.burgermeisters.de,xxx.xxx.xxx.xxx' (ECDSA) to the list of known hosts.
  <username>@www.burgermeisters.de's password: <password>
  Connected to www.burgermeisters.de.
exit

<new_passphrase> durch Password ersetzen
<username> durch den Username ersetzen


nach Fehlermeldung nochmal:
sftp <username>@www.burgermeisters.de
exit



Problem:
  Bei "cpan> install Net::SFTP::Foreign":
  Fehler: Can't locate object method "data" via package "CPAN::Modulelist" (perhaps you forgot to load "CPAN::Modulelist"?) at (eval 24) line 1.

Lösung:
  http://www.spiration.co.uk/post/1365/Can%27t%20locate%20object%20method%20%22data%22%20via%20package%20%22CPAN::Modulelist%22
  Delete the CPAN/Config.pm and the .cpan directory (in my case, /root/.cpan/)
  sudo perl -MCPAN -e shell
  install Net::SFTP::Foreign



8.13.1.4 SSH Key

Quelle: http://search.cpan.org/~ivan/Net-SSH-0.09/SSH.pm

GENERATING AND USING SSH KEYS ^

1 Generate keys
    Type:
       ssh-keygen -t rsa

    And do not enter a passphrase unless you wanted to be prompted for one during file copying.

    Here is what you will see:

       $ ssh-keygen -t rsa
       Generating public/private rsa key pair.
       Enter file in which to save the key (/home/User/.ssh/id_rsa):
       Enter passphrase (empty for no passphrase):

       Enter same passphrase again:

       Your identification has been saved in /home/User/.ssh/id_rsa.
       Your public key has been saved in /home/User/.ssh/id_rsa.pub.
       The key fingerprint is:
       5a:cd:2b:0a:cd:d9:15:85:26:79:40:0c:55:2a:f4:23 User@JEFF-CPU

2 Copy public to machines you want to upload to

    id_rsa.pub is your public key. Copy it to ~/.ssh on target machine.

    Put a copy of the public key file on each machine you want to log into. Name the copy authorized_keys (some implementations name this file authorized_keys2)

    Then type:

         chmod 600 authorized_keys

    Then make sure your home dir on the remote machine is not group or world writeable.



8.13.1.5 Zusätzliche Perl-Module installieren (2)

Quelle: http://www.perlmonks.org/?node_id=1056317

z.B.:
perl -MCPAN -e 'install Net::SNMP'



8.13.1.6 Zusätzliche Perl-Module installieren (3)

Quelle: http://www.pro-linux.de/kurztipps/2/1286/perl-module-einfach-installieren.html

Dies ist der umständliche Weg, ein Perl-Modul zu installieren:
www.cpan.org in den Browser laden
Einen Link zu dem Modul suchen
Das Modul herunterladen
Das Modul in ein geeignetes Verzeichnis entpacken

make -f Makefile.PL
make
make test
su (falls man nicht als Root angemeldet ist)
make install
exit

Das ist die Abkürzung, man muss dazu nur den Modulnamen kennen:
perl -MCPAN -e 'install Algorithm::Diff'
su (sofern man nicht als Root angemeldet ist)
cd build/Algorithm-Diff-1.10
make install
exit



8.13.1.7 Perl-Script starten

Im Perl Script sollte Folgendes in der ersten Zeile stehen:

#!/usr/bin/perl -w

  oder

#!perl

  oder auch ohne "perl"

Die Datei-Rechte sollten für Ausführbarkeit vergeben werden

Dann genügt ein Doppelklick auf die Datei
oder im Terminal:
perl dateiname.pl


8.13.1.8 Ausführbare Dateien ohne Abfrage im Terminalfenster starten

Im Dateimanager:
Bearbeiten -> Einstellungen -> Verhalten
Ausführbare Textdateien

Perl-Script-Datei perlscript.pl:
#!/usr/bin/perl
printf"Hello World!\n");
sleep(10);
exit(0);

Shell-Script-Datei script.sh:
gnome-terminal -e "perl perlscript.pl Parameter1 Parameter2 "
+++ Achtung!!! Das Leerzeichen am Ende ist wichtig!!!
Sonst schließt das Terminal sofort wieder
bzw. das Leerzeichen zum letzten Parameter dazu kommt.

Dateien ausführbar machen (z.B. Text-Datei, Perl-Script oder Shell-Script):
Im Dateimanager:
rechter Mausklick auf Datei -> Eigenschaften -> Zugriffsrechte -> Ausführen auswählen

oder:

http://www.bin-co.com/perl/perl_tk_tutorial/
http://pronix.linuxdelta.de/Perl_cgi/Perl/index.shtml
perl -MCPAN -e shell
cpan> install Bundle::CPAN
cpan> reload cpan
cpan> install Tk
cpan> bye

oder
sudo apt-get install perl-tk

http://www.linuxmintusers.de/index.php?topic=18591.0


Lösung:
http://www.linuxmintusers.de/index.php?topic=18591.0
Starter anlegen
rechter Mausklick auf Hintergrund -> Neuen Starter hier erstellen
Befehl: perl /home/burgermeister/tools/test.pl



8.13.1.9 Hintergrundprozess Textausgabe

http://de.linwiki.org/wiki/Hintergrundprozess
Ein Hintergrundprozess ist ein sich in Ausführung befindendes Programm, das keine Verbindung zur Standardein- und -ausgabe besitzt. Um unter Linux einen Prozess als Hintergrundprozess zu starten, setzt man das & Zeichen hinter dem Prozessaufruf.
Somit ist eine Textausgabe angeblich nicht möglich.

Eigene Lösung (funktioniert):

Mit folgendem Perl-Script kann ein Perl-Hintergrundprozess ein Fenster öffnen, Ausgaben machen und das Fenster wieder schließen:

output.pl:
#!/usr/bin/perl
# Tool output.pl for output from Linux Perl background task
# (C) Axel Burgermeister, 08-Sep-2014
# call from perl script:
# my $string = "Hello world!\n";
# my $displaytime = 3;
# my $waitsymbol = "&";  # "" = wait process, "&" = continue process

# system("gnome-terminal -e \"perl output.pl '$string' $displaytime  \" $waitsymbol");
my $outstring = $ARGV[0];
my $waittime  = $ARGV[1];
printf("$outstring");
sleep($waittime);
exit(0);

Test mit folgendem Perl-Script, welches sofort gestartet werden kann oder als Hintergrundprozess laufen kann:

output-test.pl (kann als Hintergrundprozess arbeiten):
#!/usr/bin/perl
# Test of output.pl
my $outstring = "Hello world!\n";
my $displaytime = 3;
my $waitsymbol = "&";  # "" = wait process, "&" = continue process
system("gnome-terminal -e \"perl /home/burgermeister/tools/output.pl '$outstring' $displaytime  \" $waitsymbol");
exit(0);


Zweite eigene Lösung:
Der Prozess kann mit Grafikfunktionen das Hintergrundbild verändern und mit einen Text versehen.


Andere Lösung:
Der Prozess kann eine Email als Ausgabe verschicken.



8.13.2 Hintergrundprozess mit weiterlaufendem Hauptprozess

Aufrufender Prozess:
#!/usr/bin/perl
system("perl tool.pl &"); # hier wird der Hintergrundprozess gestartet, das Hauptprogramm läuft weiter
exit(0);



8.13.3 Große Arrays

Datenspeicherung mit großen Arrays macht den Ablauf zunehmend langsamer:
- 4xPush-Zugriff : am Anfang 769 Schreibzugiffe/sec nach 10000 nur noch 384/sec (nach 10000 13sec pro 10000, nach 100000 26sec pro 10000, bei 100000 gesamt 199sec
- 4xIndex-Zugriff: am Anfang 769 Schreibzugiffe/sec nach 10000 nur noch 384/sec (nach 10000 14sec pro 10000, nach 100000 26sec pro 10000, bei 100000 gesamt 198sec
- 1xPush-Zugriff in einer Zeile: am Anfang 769 Schreibzugiffe/sec nach 10000 nur noch 260/sec
- Speicherreservierung macht alles extrem langsam: z.B.: my @dir1 = ("     ") x 1000000;
- Zeile in Datei-Zugriff schneller: 769 Schreibzugriffe/sec kosntant



8.13.4 Sound


8.13.4.1 Sound mit PC-Speaker

Module Audio::Beep installieren:
sudo perl -MCPAN -e shell
cpan> install Audio::Beep

-> Problem: bei Aufruf in Perl ist Audio::Beep trotz Installation nicht bekannt


Beispiel:
http://stackoverflow.com/questions/15151462/how-to-add-warning-beep-in-perl
use Audio::Beep;
my $beeper = Audio::Beep->new;
my $music = "g' f bes' c8 f d4 c8 f d4 bes c g f2";
$beeper->play ($music);




8.13.4.2 Sound-Test mit Soundkarte

http://unix.stackexchange.com/questions/1974/how-do-i-make-my-pc-speaker-beep


Alsa enthält ein Test-Kommando "speaker-test"

Beispiel:
speaker-test -t sine -f 1000 -l 1

Beispiel Funktion im Shell-Script:
_alarm() {
  ( \speaker-test --frequency $1 --test sine )&
  pid=$!
  \sleep 0.${2}s
  \kill -9 $pid
}

Aufruf mit Frequenz und Dauer:
_alarm 400 200


In Perl:
system("speaker-test -t sine -f 80");



8.13.4.3 Sound-Wiedergabe mit Soundkarte

http://wiki.ubuntuusers.de/ALSA

aplay hilft den Status von ALSA zu erkennen. Einen Überblick über die Soundkarten und deren Sub-Geräte bekommt man damit:
aplay -l  

Will man dagegen die von ALSA selbst kreierten Schnittstellen des Soundservers sehen, so benutzt man ein großes L:
aplay -L  

aplay kann aber auch direkt Sounddateien (in den Formaten voc, wav, raw und au) über die Soundkarte ausgeben. Beispiel:
aplay -D front foo.wav  


https://github.com/awwaiid/perl-noise/blob/master/eg/midi.pl
sudo perl -MCPAN -e shell
cpan> install Audio::NoiseGen




8.13.4.4 Aufnahme mit Soundkarte

http://wiki.ubuntuusers.de/ALSA
arecord
Mit arecord kann man Aufnahmequellen als Datei aufzeichnen. Beispiel:
arecord -D hw:1 -f cd foo.wav



8.13.5 Grafik und Diagramme

https://asciich.ch/wordpress/diagramme-in-perl-mit-gd-zeichnen/
http://search.cpan.org/dist/GDGraph/Graph.pm

sudo perl -MCPAN -e shell
cpan> install GD::Graph::lines
cpan> install GD::Graph::area
cpan> bye

Verwendung im Perl-Skript:
use GD::Graph::lines;
use GD::Graph::area;

Beispiel CGI-Script:
#!/usr/bin/perl
# Diagramm zeichnen

use GD::Graph::lines;

my $pathfile = "/.../www/html/temp/graf.png";
my $linkfile = "http://.../temp/graf.png";
my @x;
my @y1;
my @y2;
my $graph;
my @data;
my $gd;

for (my $i = 0; $i < 48; $i++)
{
  $x[$i] = 0.5*$i;
  $y1[$i] = 10 * sin($x[$i]);
  $y2[$i] = 10 * cos($x[$i]);
}
@data = (\@x,\@y1,\@y2);

$graph = GD::Graph::lines->new(800, 400);
$graph->set(
    title          => 'Temperatur im Tagesverlauf',

    x_label        => 'Stunde',
    x_label_skip   => 1,
    x_min_value    => 0,
    x_max_value    => 24,
    x_tick_number  => 24,

    y_label        => 'Grad Celsius',
    y_label_skip   => 1,
    y_min_value    => -15,
    y_max_value    => 35,
    y_tick_number  => 10,

    transparent    => 0,
    bgclr          => 'white',
    long_ticks     => 1,

    fgclr          => 'lgray', # Foreground Color = Gitternetz-Farbe
    dclrs          => [ qw(red green blue cyan) ], # Data Colors = Datenlinien-Farben

  ) or die $graph->error;

$gd = $graph->plot(\@data) or die $graph->error;
 
open(IMG, ">$pathfile") or die $!;
binmode IMG;
print IMG $gd->png;
close IMG;

print ("Content-type: text/html\n\n");
print ("
<html>
<head>
<title>Diagramm</title>
</head>
<body>

<img src='$linkfile' >

</body>
</html>
");

exit(0);



8.13.6 Excel-Datei lesen und schreiben

Modul Spreadsheet::WriteExcel
http://search.cpan.org/dist/Spreadsheet-WriteExcel/lib/Spreadsheet/WriteExcel.pm
sudo perl -MCPAN -e shell
cpan> install Spreadsheet::WriteExcel
cpan> quit

Modul Spreadsheet::Read
http://search.cpan.org/~hmbrand/Spreadsheet-Read/Read.pm
sudo perl -MCPAN -e shell
cpan> install Spreadsheet::Read
cpan> quit

Modul Spreadsheet::ParseExcel
http://search.cpan.org/~dougw/Spreadsheet-ParseExcel-0.65/lib/Spreadsheet/ParseExcel.pm
sudo perl -MCPAN -e shell
cpan> install Spreadsheet::ParseExcel
cpan> quit

Beispiel:
http://www.heise.de/ix/artikel/Controller-im-Glueck-505948.html


#!/usr/bin/perl

use Spreadsheet::WriteExcel;

# Create a new Excel workbook
my $workbook = Spreadsheet::WriteExcel->new('test.xls');

# Add a worksheet
$worksheet = $workbook->add_worksheet();

# Add and define a format
$format = $workbook->add_format(); # Add a format
$format->set_bold();
$format->set_color('red');
$format->set_align('center');

# Write a formatted and unformatted string, row and column notation.
$col = $row = 0;
$worksheet->write($row, $col, 'Hi Excel!', $format);
$worksheet->write(1,    $col, 'Hi Excel!');

# Write a number and a formula using A1 notation
$worksheet->write('A3', 1.2345);
$worksheet->write('A4', '=SIN(PI()/4)');


#!/usr/bin/perl -w

use strict;
use Spreadsheet::ParseExcel;

my $parser   = Spreadsheet::ParseExcel->new();
my $workbook = $parser->parse('test.xls');

if ( !defined $workbook )
  {
  die $parser->error(), ".\n";
  }

for my $worksheet ( $workbook->worksheets() )
  {
  my ( $row_min, $row_max ) = $worksheet->row_range();
  my ( $col_min, $col_max ) = $worksheet->col_range();

  for my $row ( $row_min .. $row_max )
    {
    for my $col ( $col_min .. $col_max )
      {
      my $cell = $worksheet->get_cell( $row, $col );
      next unless $cell;
      print "Row, Col    = ($row, $col)\n";
      print "Value       = ", $cell->value(),       "\n";
      print "Unformatted = ", $cell->unformatted(), "\n";
      print "\n";
      }
    }
  }


8.13.7 Formatierte Ausgabe

Zahl $value formatieren und ausgeben, Beispiel mit 2 Nachkommastellen:
$string = sprintf("%.2f",$value);
print $string;


Besucher seit 30.01.2003:

© 2013 Burgermeister  | Home | Main Server | Mirror Server | Kontakt | Impressum | Datenschutz