Friday, April 29, 2016

PerlExamples

구분자로 배열 리턴시 빈값은 제거하기

#! /usr/bin/perl

my $var = '/root:/tmp:/home:/proc::/sys:::::/dev';
my @array = split(':', $var);

for (0..$#array) {
    print "\$array[$_]: $array[$_]\n";
}
print "\n";
# same: @array = grep m/\S/, split(':', $var);
@array = grep {/\S/} split(':', $var);
for (0..$#array) {
    print "\$array[$_]: $array[$_]\n";
}
$array[0]: /root
$array[1]: /tmp
$array[2]: /home
$array[3]: /proc
$array[4]:
$array[5]: /sys
$array[6]:
$array[7]:
$array[8]:
$array[9]:
$array[10]: /dev

$array[0]: /root
$array[1]: /tmp
$array[2]: /home
$array[3]: /proc
$array[4]: /sys
$array[5]: /dev

Perl Daemonize 예제

#! /usr/bin/perl

use POSIX;

local $| = 1; # autoflush

# daemonize run
daemonize();

# 데몬화후 구문들...
while(1) {
 sleep(1);
}

# perl daemonize function
sub daemonize {
    my $_PATH_DEVNULL = "/dev/null";

    my $pid = fork();
    if ($pid > 0) {
        exit(0);
    }
    umask(0);

    POSIX::setsid() or die "POSIX::setsid() : $!";
    chdir('/') or die "chdir() : $!";
    open(STDIN, '/dev/null') or die "STDIN : $!";
    open(STDOUT, '>>/dev/null') or die "STDOUT : $!";
    open(STDERR, '>>/dev/null') or die "STDERR : $!";
}

함수 인자에 배열값 전달

#! /usr/bin/perl

sub array_ref {
    # same: $listp = \@{shift()};
    # same: $listp = shift;
    my $listp = \@{$_[0]};

    my $count = $#$listp;

    for(0..$count){
        print "\$listp->[$_]: " . $listp->[$_] . "\n";
    }

    # same: @list = @$listp
    # same: @list = @{$_[0]};
    my @list = @{shift()};

    print "\$list[$_]: " . $list[$_] . "\n" for(0..$count);
}

my @a = ('one', 'two', 'three', 'four', 'five');
array_ref(\@a);
$listp->[0]: one
$listp->[1]: two
$listp->[2]: three
$listp->[3]: four
$listp->[4]: five
$list[0]: one
$list[1]: two
$list[2]: three
$list[3]: four
$list[4]: five

배열 레퍼런스 만들기

$self->{deny_method} = ["PUT", "TEST"];

해쉬 래퍼런스 만들기

$self->{deny_method} = {"PUT" => 0, "TEST" => 1};

레퍼런스를 배열에 대입하기

my @dm = @{$self->{deny_method}};

래퍼런스를 해쉬에 대입하기

my %dm = %{$self->{deny_method}};
%srvlist = ( $self->{_srvlist} ) ? %{$self->{_srvlist}} : $self->getSrvlist($_c->{srvfile});

Command Line Options



Post a Comment