hash variable

A hash, also called an associative array, is an array in which “key” and “values” are associated as a pair. However, the array itself is characterized by being unordered. A hash variable is called a hash variable, which starts with %(percent) + 1 alphabetic character, and can use numbers, alphabetic characters and underscores (_) thereafter. Also, because case is distinguished, % and % A, for example, are treated as different things.

%fruit = ("red"=>"apple", "yellow"=>"banana");
print "$fruit{'red'}\n";

$fruit{"red"} = "apple";
$fruit{"yello"} = "banana";

%fruit = (red => "apple", yellow => "banana", purple => "grape");
@file = keys %fruit;

@file = values %fruit;
print "@file\n";

($key, $val) = each %fruit;
print "$key: $val\n";

Net::Amazon::S3::Signature::V4

cpanのサイトを見ます。
https://metacpan.org/pod/Net::Amazon::S3::Signature::V4Implementation

>Net::Amazon::S3::Signature::V4Implementation – Implements the Amazon Web Services signature version 4, AWS4-HMAC-SHA256

>This module signs an HTTP::Request to Amazon Web Services by appending an Authorization header. Amazon Web Services signature version 4, AWS4-HMAC-SHA256, is used.
なるほど、ヘッダね。
Net::Amazon::Signature::V4を使います。

use Net::Amazon::Signature::V4;

my $sig = Net::Amazon::signature::V4->new($access_key_id, $secret, $endpoint, $service);
my $req = HTTP::Request->parse( $request_string );
my $signed_req  $sig->sign($req);
...

ふむふむ、特に問題なさそうですね。。

とういか、AWSのSDK, CLIの使用に関するページだと、当然の如くperlはないな。ひどいな。。

eval – catch exceptions, execute string dynamically

You can use the eval function to catch exceptions in the case of block syntax. For string syntax, you can execute strings dynamically.

eval 

eval $string;

The one called eval string is the syntax to execute the string dynamically. Passing a string to eval will execute that string as a Perl executable statement. Errors that occur at runtime are stored in $@.

As an example, you can define a subroutine at runtime. The following example defines an eval string and a typeglob at runtime for a subroutine that return 5 foo: Temporarily allow symbolic references with no string refs.

#!/usr/bin/perl --

{
	no strict = 'refs';
	*{"foo"} = eval "sub {return 5}";
}
print "Content-type:text/html\n\n";
print $foo;

Internal Server Error

あれ?? 全然違う?? 

file出力, 生成

#!/usr/bin/perl --

print "Content-type:text/html\n\n";
$file="finance.csv";
open(IN, $file) or die "$!";
while(<IN>){
	print $_;
}
close (IN);

出力はOKだが、問題は生成の方だな

#!/usr/bin/perl --

print "Content-type:text/html\n\n";
$file="finance.csv";
$outfile="finance_out.csv";

open(IN, $file) or die "$!";
open(OUT, ">$outfile") or die "$!";

while(<IN>){
	print OUT $_;
}
close (IN);
close (OUT);

拡張子を.csvとして、OUTと指定するだけで出来るんだ。なんか拍子抜けでな。

ほう

#!/usr/bin/perl —

print “Content-type:text/html\n\n”;
$file=”finance.csv”;
$outfile=”finance_out.csv”;

open(IN, $file) or die “$!”;
open(OUT, “>$outfile”) or die “$!”;

while(){
# 改行コード除去
chomp($_);

# 各行をカンマ区切りで分割
@data = split(/,/, $_);

for ($i=0; $i<@data; $++){ $data[$i] =~ s/( | )+//g; } } close (IN); close (OUT); [/perl]

Carp::Always, Devel::KYTProf, Devel::REPL, Carp::REPL

Carp::Always
– エラーやスタックトレースの可視化
– useするだけ
warnまたはdieが出た時に、スタックトレースを引数付きで表示

Devel::KYTProf
– SQLの可視化
– useするだけ

Devel::REPL
– プロンプトで構文や式の動作を確認
– re.plコマンド

Carp::REPL
– プログラムの途中でプロンプトを起動
– dieしたところで使うなら、 perl -MCarp::REPL script.plまたはuseするだけ
– rep関数を使って任意の場所で起動

うーん、これは困った。。ログ出力か。。

Perl debug

#!/usr/bin/perl --

use strict;
use warnings;

my $message = 'Hello';
my @nums = (1, 2, 3);
my %scores = (math => 80, english => 77);

my $twice = twice(5);

$DB::single = 1;

for my $num (@nums){
	if ($num == 2) { $DB::single = 1}
	print "$num\n";
}

sub twice {
	my $num = shift;

	return $num * 2;
}

[vagrant@localhost cgi-bin]$ perl -d app.cgi

Loading DB routines from perl5db.pl version 1.32
Editor support available.

Enter h or `h h’ for help, or `man perldebug’ for more help.

main::(app.cgi:6): my $message = ‘Hello’;
DB<1> q

-dオプションでデバッガの起動ということだが、うむ、イマイチよくわからん。
q でデバック終了。
n でシングルステップ

違う例で見てみる。

#!/usr/bin/perl —

use strict;
use warnings;

my $num = 3;
for(my $i=1;$i<=3;$i++){ print $num*$i."\n"; } [/perl]

[vagrant@localhost cgi-bin]$ perl app.cgi
3
6
9
[vagrant@localhost cgi-bin]$ perl -d app.cgi

Loading DB routines from perl5db.pl version 1.32
Editor support available.

Enter h or `h h’ for help, or `man perldebug’ for more help.

main::(app.cgi:6):      my $num = 3;
  DB<1> n
main::(app.cgi:9):      }
  DB<1> n
main::(app.cgi:7):      for(my $i=1;$i<=3;$i++){
  DB<1> n
main::(app.cgi:8):              print $num*$i.”\n”;
  DB<1> n
3
main::(app.cgi:8):              print $num*$i.”\n”;
  DB<1> n
6
main::(app.cgi:8):              print $num*$i.”\n”;
  DB<1> n
9
Debugged program terminated.  Use q to quit or R to restart,
  use o inhibit_exit to avoid stopping after program termination,
  h q, h R or h o to get additional info.
  DB<1> q

なるほど、1行ずつ見ていくのね。

Perl’s sysopen

Perl’s sysopen is a function equivalent to C’s fopen. Specify a file handle for the first argument, a file name for the second argument, and an open flag for the third argument. If necessary, you can specify the permission in octal in the fourth argument, and the default permission is 0666.

#!/usr/bin/perl --

use strict;
use warnings;

print "Content-type:text/html\n\n";
use Fcntl;

my $file = test;

sysopen(my $fh, $file, O_WRONLY | O_EXCL | O_CREAT)
  or die "Couldn't open $file : $!";
close($fh);

あれ、上手くいかない。。
sysopen関数を使えば、オープンモードを細かく指定できるらしいが。。ぬぬ。

perl undef

Undefined values can be set using the undef function. Alternatively, the value of the variable specified in the argument is undefined.

#!/usr/bin/perl --

use strict;
use warnings;

print "Content-type:text/html\n\n";
my $name = "Kimoto";
$name = undef;

if (defined $name){
	print "defined";
} else {
	print "Undef";
}

なるほどー

Perl DBIでselect

mysql> use test
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables;
+----------------+
| Tables_in_test |
+----------------+
| items          |
| name           |
| news           |
| user           |
+----------------+
4 rows in set (0.00 sec)

mysql> select * from items;
+---------+---------+-------+
| item_id | name    | price |
+---------+---------+-------+
|       1 | U+1F363 |  NULL |
+---------+---------+-------+
1 row in set (0.00 sec)

#!/usr/bin/perl --

use CGI;
use DBI;

print "Content-type:text/html\n\n";
print "hello";
my $user = 'root';
my $passwd = '';
my $db = DBI->connect('DBI:mysql:test:localhost', $user, $passwd);
my $sth = $db->prepare("select * from items;");
$sth->execute();
while (my $ary_ref = $sth->fetchrow_arrayref){
	my($a, $b) = @$ary_ref;
	print "$a, $b\n";
}
$sth->finish;
$dbh->disconnect;

OKなんだけど、これ、tableで表示するとき、whileが2つになるけど、どうするんだっけ?

print "<table>";
while (my $ary_ref = $sth->fetchrow_arrayref){
	my($a, $b) = @$ary_ref;
	print "<tr><td>$a</td><td>$b</td></tr>\n";
}
print "</table>";

tableはtableで良いんだが。。

Perl mysqlで文字化けするとき

Perlで入れて、文字化けしてる!?

my $user = 'root';
my $passwd = '';
my $db = DBI->connect('DBI:mysql:click:localhost', $user, $passwd);
my $sth = $db->prepare("INSERT INTO _mng(user_id, password, last_name, first_name, dept) VALUES (?, ?, ?, ?, ?)");
$sth->execute($user_id, $password, $last_name, $first_name, $dept);
+---------+----------+----------------+--------------+---------------------+----------------------+------------------------+----------------+----------------------+-----------------------+---------------------------+---------------+-------------+---------------+-------------+
| aaa     | hoge     | �田         | 太郎       | 管�部           | NULL                 | NULL                   |           NULL | NULL                 | NULL                  | NULL                      | NULL          | NULL        | NULL          | NULL        |
| eda     | hoge     | 江藤         | �          | 管�部           | NULL                 | NULL                   |           NULL | NULL                 | NULL                  | NULL                      | NULL          | NULL        | NULL          | NULL        |
| hoge    | hoge     | 山田         | 太郎       | 管�部           | NULL                 | NULL                   |           NULL | NULL                 | NULL                  | NULL                      | NULL          | NULL        | NULL          | NULL        |
| ykk     | hoge     | 高橋         | �          | 管�部           | NULL                 | NULL                   |           NULL | NULL                 | NULL                  | NULL                      | NULL          | NULL        | NULL          | NULL        |
+---------+----------+----------------+--------------+---------------------+----------------------+------------------------+----------------+----------------------+-----------------------+---------------------------+---------------+-------------+---------------+-------------+
4 rows in set (0.00 sec)

set name utf8がない模様

my $user = ‘root’;
my $passwd = ”;
my $db = DBI->connect(‘DBI:mysql:click:localhost’, $user, $passwd);
my $sth = $db->prepare(“INSERT INTO mng(user_id, password, last_name, first_name, dept) VALUES (?, ?, ?, ?, ?)”);
$db->do(“set names utf8”);
$sth->execute($user_id, $password, $last_name, $first_name, $dept);

+———+———-+—————-+————–+———————+———————-+————————+—————-+———————-+———————–+—————————+—————+————-+—————+————-+
| aaa | hoge | �田 | 太郎 | 管�部 | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL |
| eda | hoge | 江藤 | � | 管�部 | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL |
| hoge | hoge | 山田 | 太郎 | 管�部 | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL |
| sakura | sakura | さくら | たかし | 管理部 | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL |
| ykk | hoge | 高橋 | � | 管�部 | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL |
+———+———-+—————-+————–+———————+———————-+————————+—————-+———————-+———————–+—————————+—————+————-+—————+————-+
5 rows in set (0.00 sec)

日本語で入りましたねー