Download Perl module(CPAN)

perl 2009. 7. 31. 21:46

perl -MCPAN -e shell

cpan>  install <Module Name>
for example : install XML::Schema

'perl' 카테고리의 다른 글

Download Perl module(CPAN)  (0) 2009.07.31
remote shell command  (0) 2009.07.31
웹 막음, 오픈 (서비스 오픈 전에 사용)  (0) 2009.07.31
CPAN 이용하기  (0) 2008.09.27
펄에서 특정 패턴 확인하기  (0) 2008.07.17
반올림(또는 버림) 함수  (0) 2008.06.07
Posted by 김용환 '김용환'

댓글을 달아 주세요

remote shell command

perl 2009. 7. 31. 21:45

아주 간단한 rshell을 이용한 remote shell command..
#!/usr/bin/perl
# remote commandd (host, rcmd, lcmd)
sub rcmd {
  my $RSH = "/usr/local/bin/rsh";
  chomp $RSH;
  my $RESULT = "";
  if($#_ == 1) {
     $RESULT = `$RSH $_[0] $_[1]`;
  } else {
    $RESULT = `$RSH $_[0] $_[1] | $_[2]`;
  }
  chomp $RESULT;
    return $RESULT;
}
rcmd("a55384", "ls -al");

'perl' 카테고리의 다른 글

Download Perl module(CPAN)  (0) 2009.07.31
remote shell command  (0) 2009.07.31
웹 막음, 오픈 (서비스 오픈 전에 사용)  (0) 2009.07.31
CPAN 이용하기  (0) 2008.09.27
펄에서 특정 패턴 확인하기  (0) 2008.07.17
반올림(또는 버림) 함수  (0) 2008.06.07
Posted by 김용환 '김용환'

댓글을 달아 주세요


서비스 오픈하기 전에 내부에서 먼저 웹을 띄워보고(외부는 접근못하게 한 후), QA 확인 체크한 후, 오픈하고 싶을 때가 있다.

그럴 때는 보통 다음의 방법을 사용한다.
1.  도메인이 오픈 시간에 오픈한다.
2. 티져를 먼져오픈해놓고, 오픈 시간에 진짜 웹 서비스를 배포한다.
3. 도메인 신청이 되어 있지만, 아직 보여주고 싶지 않을 때는 아파치를 내리기

이 외에 웹 어플리케이션은 그대로 두고, 방화벽으로 막는 경우가 있다. 다른 것에 비해서 미리 준비시키게 하고, 단순히 스크립트만 실행하면 되기 까닭에 편한 부분이 존재한다.

(웹 오픈 80 및 8080 포트 막기) 스크립트
closeweb.pl
#!/usr/bin/perl
# 이 스크립트는 리얼 프로젝트가 오픈하기 전에 방화벽을 열어
# 특정 서버에 대해서만 리얼 서버에 접근하여 테스트할 수 있도록 만들어진 스크립트이다.
# 정책은 다음과 같다.
# 1) ifconfig를 이용하여 ip정보를 얻어서 방화벽을 넘을 수 있도록 허용한다.
# 2) monitor ip(CIO 토파즈 서버들에 대해서 방화벽을 넘어올 수 있도록 허용한다.
# 3) permitted ip는 localhost, L4, host ip에 대해서의 요청은 방화벽을 지날 수 있도록 한다.

my $string=`/sbin/ifconfig | grep 'inet addr' | awk '{print \$2}'`;
my @ifconfig_iplist = $string =~ /addr:(\d+.\d+.\d+.\d+)/g;
#print $_, "\n" foreach(@array);
@permitted = qw(
192.1688.14.0/24
# 내부 ip를 적어준다.
);
my @monitor = qw(
# 모니터링 Ip를 적어준다. 보통 l4나 토파즈같은 녀석이다.
);
foreach $ip (@ifconfig_iplist) {
    chomp $ip;
    `/sbin/iptables -I INPUT -p tcp -s $ip -j ACCEPT`;
}
foreach $ip (@monitor) {
    chomp $ip;
    `/sbin/iptables -I INPUT -p tcp -s $ip -j ACCEPT`;
}
foreach $ip (@permitted) {
    chomp $ip;
    `/sbin/iptables -I INPUT -p tcp -s $ip -j ACCEPT`;
}
`/sbin/iptables -A INPUT -p tcp --dport 80 -j DROP`;
`/sbin/iptables -A INPUT -p tcp --dport 8080 -j DROP`;

 



웹 오픈이 개시되면, 기존의 방화벽을 오픈해 주면 된다.
openweb.pl
#!/usr/bin/perl
my $result = `/sbin/iptables -F`;

 

'perl' 카테고리의 다른 글

Download Perl module(CPAN)  (0) 2009.07.31
remote shell command  (0) 2009.07.31
웹 막음, 오픈 (서비스 오픈 전에 사용)  (0) 2009.07.31
CPAN 이용하기  (0) 2008.09.27
펄에서 특정 패턴 확인하기  (0) 2008.07.17
반올림(또는 버림) 함수  (0) 2008.06.07
Posted by 김용환 '김용환'

댓글을 달아 주세요

CPAN 이용하기

perl 2008. 9. 27. 03:28

1. cpan 싸이트에서 검색해서 다운로드

 

 

2. 리눅스에서 다음의 명령어 사용

perl -MCPAN -e 'shell'

 

쉘에서 다음과 같이 사용
install DBD::mysql


 

Posted by 김용환 '김용환'

댓글을 달아 주세요

 

 

펄에서 스트링에 대해서 특정 패턴이 나타나는지 확인하고 싶을 때 있다.  이때는 펄의 RE를 사용해 보자. 간단한 예가 밑에 있어서 사용.

 

     if ($r =~ m/error getting credentials: Ticket expired/) {
        print "** $HOST server 리스타트 실패되었습니다. 커보러스 티켓이 expired되었습니다. kinit -f {계정} 해주시면 사용하실수 있습니다. \n\n"
    } else {
        print ("$HOST server 리스타트가 완료되었습니다.\n");
    } 

 

 

http://www.somacon.com/p127.php

Section 1: Basic matching and substitution

Declare a local variable called $mystring.

my $mystring;

Assign a value (string literal) to the variable.

$mystring = "Hello world!";

Does the string contains the word "World"?

if($mystring =~ m/World/) { print "Yes"; }

No, it doesn't. The binding operator =~ with the match operator m// does a pattern search on $mystring and returns true if the pattern is found. The pattern is whatever is between the m/ and the trailing /. (Note, there is no such thing as a ~= operator, and using it will give a compile error.)

Does the string contains the word "World", ignoring case?

if($mystring =~ m/World/i) { print "Yes"; }

Yes, it does. The pattern modifier i immediately after the trailing / changes the match to be case-insensitive.

I want "Hello world!" to be changed to "Hello mom!" instead.

$mystring =~ s/world/mom/;
print $mystring;

Prints "Hello mom!". The substitution operator s/// replaces the pattern between the s/ and the middle /, with the pattern between the middle / and last /. In this case, "world" is replaced with the word "mom".

Now change "Hello mom!" to say "Goodby mom!".

$mystring =~ s/hello/Goodbye/;
print $mystring;

This does not substitute, and prints "Hello mom!" as before. By default, the search is case sensitive. As before, use the pattern modifier i immediately after the trailing / to make the search case-insensitive.

Okay, ignoring case, change "Hello mom!" to say "Goodby mom!".

$mystring =~ s/hello/Goodbye/i;
print $mystring;

Prints "Goodby mom!".


Section 2: Extracting substrings

I want to see if my string contains a digit.

$mystring = "[2004/04/13] The date of this article.";
if($mystring =~ m/\d/) { print "Yes"; }

Prints "Yes". The pattern \d matches any single digit. In this case, the search will finish as soon as it reads the "2". Searching always goes left to right.

Huh? Why doesn't "\d" match the exact characters '\' and 'd'?

This is because Perl uses characters from the alphabet to also match things with special meaning, like digits. To differentiate between matching a regular character and something else, the character is immediately preceded by a backslash. Therefore, whenever you read '\' followed by any character, you treat the two together as one symbol. For example, '\d' means digit, '\w' means alphanumeric characters including '_', '\/' means forward slash, and '\\' means match a single backslash. Preceding a character with a '\' is called escaping, and the '\' together with its character is called an escape sequence.

Okay, how do I return the first matching digit from my string?

$mystring = "[2004/04/13] The date of this article.";
if($mystring =~ m/(\d)/) {
	print "The first digit is $1.";
}

Prints "The first digit is 2." In order to designate a pattern for extraction, one places parenthesis around the pattern. If the pattern is matched, it is returned in the Perl special variable called $1. If there are multiple parenthesized expressions, then they will be in variables $1, $2, $3, etc.

Huh? Why doesn't '(' and ')' match the parenthesis symbols exactly?

This is because the designers of regular expressions felt that some constructs are so common that they should use unescaped characters to represent them. Besides parentheses, there are a number of other characters that have special meanings when unescaped, and these are called metacharacters. To match parenthesis characters or other metacharacters, you have to escape them like '\(' and '\)'. They designed it for their convenience, not to make it easy to learn.

Okay, how do I extract a complete number, like the year?

$mystring = "[2004/04/13] The date of this article.";
if($mystring =~ m/(\d+)/) {
	print "The first number is $1.";
}

Prints "The first number is 2004." First, when one says "complete number", one really means a grouping of one or more digits. The pattern quantifier + matches one or more of the pattern that immediately precedes it, in this case, the \d. The search will finish as soon as it reads the "2004".

How do I print all the numbers from the string?

$mystring = "[2004/04/13] The date of this article.";
while($mystring =~ m/(\d+)/g) {
	print "Found number $1.";
}

Prints "Found number 2004. Found number 04. Found number 13. ". This introduces another pattern modifier g, which tells Perl to do a global search on the string. In other words, search the whole string from left to write.

How do I get all the numbers from the string into an array instead?

$mystring = "[2004/04/13] The date of this article.";
@myarray = ($mystring =~ m/(\d+)/g);
print join(",", @myarray);

Prints "2004,04,13". This does the same thing as before, except assigns the returned values from the pattern search into myarray.


Section 3: Common tasks

How do I extract everything between a the words "start" and "end"?

$mystring = "The start text always precedes the end of the end text.";
if($mystring =~ m/start(.*)end/) {
	print $1;
}

Prints text always precedes the end of the . The pattern .* is two different metacharacters that tell Perl to match everything between the start and end. Specifically, the metacharacter . means match any symbol except new line. The pattern quantifier * means match zero or more of the preceding symbol.

That isn't exactly what I expected. How do I extract everything between "start" and the first "end" encountered?

$mystring = "The start text always precedes the end of the end text.";
if($mystring =~ m/start(.*?)end/) {
	print $1;
}

Prints text always precedes the . By default, the quantifiers are greedy. This means that when you say .*, Perl matches every character (except new line) all the way to the end of the string, and then works backward until it finds end. To make the pattern quantifier miserly, you use the pattern quantifier limiter ?. This tells Perl to match as few as possible of the preceding symbol before continuing to the next part of the pattern.

'perl' 카테고리의 다른 글

웹 막음, 오픈 (서비스 오픈 전에 사용)  (0) 2009.07.31
CPAN 이용하기  (0) 2008.09.27
펄에서 특정 패턴 확인하기  (0) 2008.07.17
반올림(또는 버림) 함수  (0) 2008.06.07
펄에서 List안에 List를 넣기 (또는 2차원 배열 array)  (0) 2008.06.07
Array 쪽 팁  (0) 2008.06.07
Posted by 김용환 '김용환'

댓글을 달아 주세요

sub round {
    my $number = shift; 
    return int($number + .5);
}

또는

 

return int($number + .5 * ($number <=> 0));

 

 

또는

 

 

use POSIX qw(ceil floor);

$num = 42.4;

print "Floor returns: ", floor($num), "\n";

print "Ceil returns:  ", ceil($num), "\n";

<결과>

Floor returns: 42
Ceil returns:  43

 

 

'perl' 카테고리의 다른 글

CPAN 이용하기  (0) 2008.09.27
펄에서 특정 패턴 확인하기  (0) 2008.07.17
반올림(또는 버림) 함수  (0) 2008.06.07
펄에서 List안에 List를 넣기 (또는 2차원 배열 array)  (0) 2008.06.07
Array 쪽 팁  (0) 2008.06.07
Array 다루기 #2  (0) 2008.06.05
Posted by 김용환 '김용환'

댓글을 달아 주세요

펄도 2차원 배열(List 의 List) 를 만들 수 있다.

 

출처 :http://www.perl.com/doc/manual/html/pod/perllol.html

 

 

Declaration and Access of Lists of Lists

The simplest thing to build is a list of lists (sometimes called an array of arrays). It's reasonably easy to understand, and almost everything that applies here will also be applicable later on with the fancier data structures.

A list of lists, or an array of an array if you would, is just a regular old array @LoL that you can get at with two subscripts, like $LoL[3][2]. Here's a declaration of the array:

    # assign to our array a list of list references
    @LoL = (
           [ "fred", "barney" ],
           [ "george", "jane", "elroy" ],
           [ "homer", "marge", "bart" ],
    );

    print $LoL[2][2];
  bart

Now you should be very careful that the outer bracket type is a round one, that is, a parenthesis. That's because you're assigning to an @list, so you need parentheses. If you wanted there not to be an @LoL, but rather just a reference to it, you could do something more like this:

    # assign a reference to list of list references
    $ref_to_LoL = [
        [ "fred", "barney", "pebbles", "bambam", "dino", ],
        [ "homer", "bart", "marge", "maggie", ],
        [ "george", "jane", "alroy", "judy", ],
    ];

    print $ref_to_LoL->[2][2];

Notice that the outer bracket type has changed, and so our access syntax has also changed. That's because unlike C, in perl you can't freely interchange arrays and references thereto. $ref_to_LoL is a reference to an array, whereas @LoL is an array proper. Likewise, $LoL[2] is not an array, but an array ref. So how come you can write these:

    $LoL[2][2]
    $ref_to_LoL->[2][2]

instead of having to write these:

    $LoL[2]->[2]
    $ref_to_LoL->[2]->[2]

Well, that's because the rule is that on adjacent brackets only (whether square or curly), you are free to omit the pointer dereferencing arrow. But you cannot do so for the very first one if it's a scalar containing a reference, which means that $ref_to_LoL always needs it.


Growing Your Own

That's all well and good for declaration of a fixed data structure, but what if you wanted to add new elements on the fly, or build it up entirely from scratch?

First, let's look at reading it in from a file. This is something like adding a row at a time. We'll assume that there's a flat file in which each line is a row and each word an element. If you're trying to develop an @LoL list containing all these, here's the right way to do that:

    while (<>) {
        @tmp = split;
        push @LoL, [ @tmp ];
    }

You might also have loaded that from a function:

    for $i ( 1 .. 10 ) {
        $LoL[$i] = [ somefunc($i) ];
    }

Or you might have had a temporary variable sitting around with the list in it.

    for $i ( 1 .. 10 ) {
        @tmp = somefunc($i);
        $LoL[$i] = [ @tmp ];
    }

It's very important that you make sure to use the [] list reference constructor. That's because this will be very wrong:

    $LoL[$i] = @tmp;

You see, assigning a named list like that to a scalar just counts the number of elements in @tmp, which probably isn't what you want.

If you are running under use strict, you'll have to add some declarations to make it happy:

    use strict;
    my(@LoL, @tmp);
    while (<>) {
        @tmp = split;
        push @LoL, [ @tmp ];
    }

Of course, you don't need the temporary array to have a name at all:

    while (<>) {
        push @LoL, [ split ];
    }

You also don't have to use push(). You could just make a direct assignment if you knew where you wanted to put it:

    my (@LoL, $i, $line);
    for $i ( 0 .. 10 ) {
        $line = <>;
        $LoL[$i] = [ split ' ', $line ];
    }

or even just

    my (@LoL, $i);
    for $i ( 0 .. 10 ) {
        $LoL[$i] = [ split ' ', <> ];
    }

You should in general be leery of using potential list functions in a scalar context without explicitly stating such. This would be clearer to the casual reader:

    my (@LoL, $i);
    for $i ( 0 .. 10 ) {
        $LoL[$i] = [ split ' ', scalar(<>) ];
    }

If you wanted to have a $ref_to_LoL variable as a reference to an array, you'd have to do something like this:

    while (<>) {
        push @$ref_to_LoL, [ split ];
    }

Now you can add new rows. What about adding new columns? If you're dealing with just matrices, it's often easiest to use simple assignment:

    for $x (1 .. 10) {
        for $y (1 .. 10) {
            $LoL[$x][$y] = func($x, $y);
        }
    }

    for $x ( 3, 7, 9 ) {
        $LoL[$x][20] += func2($x);
    }

It doesn't matter whether those elements are already there or not: it'll gladly create them for you, setting intervening elements to undef as need be.

If you wanted just to append to a row, you'd have to do something a bit funnier looking:

    # add new columns to an existing row
    push @{ $LoL[0] }, "wilma", "betty";

Notice that I couldn't say just:

    push $LoL[0], "wilma", "betty";  # WRONG!

In fact, that wouldn't even compile. How come? Because the argument to push() must be a real array, not just a reference to such.


Access and Printing

Now it's time to print your data structure out. How are you going to do that? Well, if you want only one of the elements, it's trivial:

    print $LoL[0][0];

If you want to print the whole thing, though, you can't say

    print @LoL;         # WRONG

because you'll get just references listed, and perl will never automatically dereference things for you. Instead, you have to roll yourself a loop or two. This prints the whole structure, using the shell-style for() construct to loop across the outer set of subscripts.

    for $aref ( @LoL ) {
        print "\t [ @$aref ],\n";
    }

If you wanted to keep track of subscripts, you might do this:

    for $i ( 0 .. $#LoL ) {
        print "\t elt $i is [ @{$LoL[$i]} ],\n";
    }

or maybe even this. Notice the inner loop.

    for $i ( 0 .. $#LoL ) {
        for $j ( 0 .. $#{$LoL[$i]} ) {
            print "elt $i $j is $LoL[$i][$j]\n";
        }
    }

As you can see, it's getting a bit complicated. That's why sometimes is easier to take a temporary on your way through:

    for $i ( 0 .. $#LoL ) {
        $aref = $LoL[$i];
        for $j ( 0 .. $#{$aref} ) {
            print "elt $i $j is $LoL[$i][$j]\n";
        }
    }

Hmm... that's still a bit ugly. How about this:

    for $i ( 0 .. $#LoL ) {
        $aref = $LoL[$i];
        $n = @$aref - 1;
        for $j ( 0 .. $n ) {
            print "elt $i $j is $LoL[$i][$j]\n";
        }
    }


Slices

If you want to get at a slice (part of a row) in a multidimensional array, you're going to have to do some fancy subscripting. That's because while we have a nice synonym for single elements via the pointer arrow for dereferencing, no such convenience exists for slices. (Remember, of course, that you can always write a loop to do a slice operation.)

Here's how to do one operation using a loop. We'll assume an @LoL variable as before.

    @part = ();
    $x = 4;
    for ($y = 7; $y < 13; $y++) {
        push @part, $LoL[$x][$y];
    }

That same loop could be replaced with a slice operation:

    @part = @{ $LoL[4] } [ 7..12 ];

but as you might well imagine, this is pretty rough on the reader.

Ah, but what if you wanted a two-dimensional slice, such as having $x run from 4..8 and $y run from 7 to 12? Hmm... here's the simple way:

    @newLoL = ();
    for ($startx = $x = 4; $x <= 8; $x++) {
        for ($starty = $y = 7; $y <= 12; $y++) {
            $newLoL[$x - $startx][$y - $starty] = $LoL[$x][$y];
        }
    }

We can reduce some of the looping through slices

    for ($x = 4; $x <= 8; $x++) {
        push @newLoL, [ @{ $LoL[$x] } [ 7..12 ] ];
    }

If you were into Schwartzian Transforms, you would probably have selected map for that

    @newLoL = map { [ @{ $LoL[$_] } [ 7..12 ] ] } 4 .. 8;

Although if your manager accused of seeking job security (or rapid insecurity) through inscrutable code, it would be hard to argue. :-) If I were you, I'd put that in a function:

    @newLoL = splice_2D( \@LoL, 4 => 8, 7 => 12 );
    sub splice_2D {
        my $lrr = shift;        # ref to list of list refs!
        my ($x_lo, $x_hi,
            $y_lo, $y_hi) = @_;

        return map {
            [ @{ $lrr->[$_] } [ $y_lo .. $y_hi ] ]
        } $x_lo .. $x_hi;
    }

'perl' 카테고리의 다른 글

펄에서 특정 패턴 확인하기  (0) 2008.07.17
반올림(또는 버림) 함수  (0) 2008.06.07
펄에서 List안에 List를 넣기 (또는 2차원 배열 array)  (0) 2008.06.07
Array 쪽 팁  (0) 2008.06.07
Array 다루기 #2  (0) 2008.06.05
Array 다루기 #1  (0) 2008.06.05
Posted by 김용환 '김용환'

댓글을 달아 주세요

Array 쪽 팁

perl 2008. 6. 7. 01:33

 

1. Array를 이용하여 Stack처럼 사용하기

 my @stack;
push(@stack, 7, 6, "go"); 
my $action = pop @stack; 
my $value = pop(@stack) + pop(@stack);    # 13이 나옴


 

 

2. Array를 Queue처럼 사용하기

 use strict;
my @queue;
unshift (@queue, "Customer 1");
unshift (@queue, "Customer 2");
unshift (@queue, "Customer 3");  # @queue안에 ("Customer 3" "Customer 2" "Customer 1") 존재

my $item = pop(@queue);         # @queue 에는 ("Customer 3" "Customer 2")
print "Servicing $item\n";       # 출력  Servicing Customer 1
$item = pop(@queue);            # @queue 에는 ("Customer 3")
print "Servicing $item\n";       # 출력  Servicing Customer 2

 

 

3. Array를 Array에 대입

@arr2 = @arr1[2..5];            # @arr 의 2번부터 5번까지 @arr2에 대입

@arr2 = ( @arr, $a, $b ); #   #@arr와 $a, $b를 합쳐 @arra2에 대입

( $name, $age, $home, $sex )  = @personal  # @personal의 값들을 각각의 변수에 대입

 

4.

'perl' 카테고리의 다른 글

반올림(또는 버림) 함수  (0) 2008.06.07
펄에서 List안에 List를 넣기 (또는 2차원 배열 array)  (0) 2008.06.07
Array 쪽 팁  (0) 2008.06.07
Array 다루기 #2  (0) 2008.06.05
Array 다루기 #1  (0) 2008.06.05
Passing Parameters to Functions  (0) 2008.06.05
Posted by 김용환 '김용환'

댓글을 달아 주세요

Array 다루기 #2

perl 2008. 6. 5. 02:27

 

출처 :

http://mailman.linuxchix.org/pipermail/courses/2003-November/001359.html

 

LinuxChix Perl Course Part 16: Array Functions

1) Introduction
2) Re-Visiting Old Perl Functions
3) Six Simple Functions
4) Consider the Context
5) Exercise
6) Answers to Previous Exercises
7) Past Information
8) Credits
9) Licensing

             -----------------------------------

1) Introduction

Perl includes many functions that make handling arrays a breeze.

Some of these functions are quite versatile, i.e., you can change the
way they work if you need a slightly different behaviour. We could never
get through all the different customisations that can be done, but you
can find out more about any one of these functions by typing
"perldoc -f <function name>" at the command-line.

             -----------------------------------

2) Re-Visiting Old Perl Functions

Some Perl functions that we've already seen will accept either scalars
or lists. For example, we've seen the "chomp" function used with
scalars, but it can also be used with a list (in which case it chomps
every element of the list):

   chomp($scalar);
   chomp(@array);
   chomp($a, $list, $of, $scalars);

But not all Perl functions can do this. For example, the "uc" function
capitalises all the letters in a string, but it won't accept a list.
Always RTFM to make sure.

             -----------------------------------

3) Six Simple Functions

We're going to start with

a) split - splits a string into an array
b) join - combines an array to form a string
c) reverse - reverses the order of an array (first element becomes last)
d) sort - puts the array in alphabetical order (NOT numerical order)
e) push - adds one or more values to the end of an array
f) pop - removes and returns the last element of an array

Examples:

   my @arr = split( /[#!]+/, 'foo###bar!!!baz' );
       # Now @arr = ('foo', 'bar', 'baz')
   print join('**', @arr);      # Output is: "foo**bar**baz"
   @arr = reverse(@arr);        # Now @arr = ('baz', 'bar', 'foo')
   @arr = sort(@arr);           # Now @arr = ('bar', 'baz', 'foo')
   my $x = pop(@arr);           # Now $x='baz' and @arr=('foo', 'bar')
   push(@arr, 'Bob', 'Jane');   # Now: ('foo', 'bar', 'Bob', 'Jane')

Note that only the functions "push" and "pop" change the array variable
passed in. This means that the other functions can take any list, not
just an array:

   my @arr = ('foo', 'bar', 'baz');
   print join('**', @arr);      # Output is: "foo**bar**baz"
   print join('**', 'foo', 'bar', 'baz');  # Same as previous line
   print join('**', 'A', @arr, 'B');  # Output: "A**foo**bar**baz**B"

             -----------------------------------

4) Consider the Context

Many Perl functions and operators behave differently depending on the
"context". Perl has three possible contexts: scalar context, list
context and void context:

   my @arr = ('foo', 'bar', 'baz');
   my @a = reverse(@arr);       # Array context
   my $s = reverse(@arr);       # Scalar context
   reverse(@arr);               # Void context

   print "@a\n";       # Output is: baz bar foo
   print "$s\n";       # Output is: zabraboof (foobarbaz backwards)

Note that the context is determined by how the return value is used, NOT
the parameters passed to the function/operator. This is quite Perl-like;
most languages have functions that always return the same value, no
matter how it's used.

The use of an array (variable) in scalar context returns the length of
the array:

   my @array = ('foo', 'bar', 'baz');
   my $scalar = @array;
   print "$scalar\n";      # Output is 3.

But don't try this with a literal list:

   my $scalar = ('foo', 'bar', 'baz');       # Warnings generated here.
   print "$scalar\n";      # Output is baz.

In the above cases the context was obvious because we assigned to an
array or scalar variable. But the context can also be indicated by an
operator. For example, arithmetic operators are all scalar, as is string
concatenation:

   print "The length of the array is: " . @array . "\n";

We can also force scalar context by using the "scalar" operator:

   ($length_a, $length_b) = (scalar @a, scalar @b);

"man perlfunc" tells us: "There is no equivalent operator to force an
expression to be interpolated in list context because in practice, this
is never needed."

             -----------------------------------

5) Exercise

Write a Perl program that reads /etc/passwd and outputs just a list of
usernames and UIDs, ordered alphabetically by username. Remember: There
Is More Than One Way To Do It.

             -----------------------------------

6) Answers to Previous Exercises

a) Here is a tail program that works on even a small number of lines.

   #!/usr/bin/perl -w
   use strict;

   my @lines = <>;

   my $lines_to_output = @lines;     # Get number of lines.
   $lines_to_output = 10 if $lines_to_output > 10;  # Limit number of lines.

   print @lines[ -$lines_to_output .. -1 ];

b) Here is a reversal algorithm.

   #!/usr/bin/perl -w
   use strict;

   my @array = qw/A B C D E F G/;

   my @result;
   foreach my $element (@array) {
     @result = ($element, @result);
   }

   print "Result is: @result\n";

As you might guess, it would be a little more efficient to use "push"
and "pop", but we hadn't seen these functions last week. (Calling the
"reverse" function would be more efficient still! :-)

'perl' 카테고리의 다른 글

펄에서 List안에 List를 넣기 (또는 2차원 배열 array)  (0) 2008.06.07
Array 쪽 팁  (0) 2008.06.07
Array 다루기 #2  (0) 2008.06.05
Array 다루기 #1  (0) 2008.06.05
Passing Parameters to Functions  (0) 2008.06.05
Perl의 String 관련 함수  (0) 2008.03.22
Posted by 김용환 '김용환'

댓글을 달아 주세요

Array 다루기 #1

perl 2008. 6. 5. 02:25

 

perl 코드에서 보면, Array를 파라미터로 넘겨서 처리하는 좋은 예제가 있다.

좋은 참조 자료를 바탕으로 재구성하였다.

 

출처 : http://www.webbasedprogramming.com/Perl-5-By-Example/ch5.htm#ExampleUsingtheParameterArray

 

#1

 

 
firstSub(1, 2, 3, 4, 5, 6);
firstSub(1..3);
firstSub("A".."Z");

sub firstSub {
    $numParameters = @_;
    print("The number of parameters is $numParameters\n");
}
This program prints out:
The number of parameters is 6
The number of parameters is 3
The number of parameters is 26

 

 

#2

 

 
areaOfRectangle(2, 3);
areaOfRectangle(5, 6);

sub areaOfRectangle {
    ($height, $width) = @_;

    $area = $height * $width;

    print("The height is $height. The width is $width.
        The area is $area.\n\n");
}
This program prints out:
The height is 2. The width is 3.
        The area is 6.

The height is 5. The width is 6.
        The area is 30.

 

 

 

#3

 
@array = (0..5);
print("Before function call, array = @array\n");
firstSub(@array);
print("After function call, array =  @array\n");

sub firstSub{
    $_[0] = "A";
    $_[1] = "B";
}

This program prints:

Before function call, array =  0 1 2 3 4 5
After function call, array =   A B 2 3 4 5

 

#4

 

@array = (0..5); print("Before function call, array = @array\n"); firstSub(@array); print("After function call, array = @array\n"); sub firstSub{ ($firstVar, $secondVar) = @_; $firstVar = "A"; $secondVar = "B"; }

This program prints:

Before function call, array =  0 1 2 3 4 5
After function call, array =   0 1 2 3 4 5

 

#5

 

@array = (0..5);
print("Before function call, array = @array\n");
firstSub(@array);
print("After function call, array =  @array\n");

sub firstSub{
    ($firstVar, $secondVar) = @_;

    $firstVar = "A";
    $secondVar = "B";
}

This program prints:

Before function call, array =  0 1 2 3 4 5
After function call, array =   0 1 2 3 4 5

 

 

#6

 

$firstVar = 10;
@array    = (0..5);

print("Before function call\n");
print("\tfirstVar = $firstVar\n");
print("\tarray    = @array\n");

firstSub(@array);

print("After function call\n");
print("\tfirstVar = $firstVar\n");
print("\tarray    = @array\n");

sub firstSub{
    ($firstVar, $secondVar) = @_;

    $firstVar = "A";
    $secondVar = "B";
}

This program prints:

Before function call
        firstVar = 10
        array    = 0 1 2 3 4 5

After function call
        firstVar = A
        array    = 0 1 2 3 4 5

 

#6

 

firstSub("AAAAA", "BBBBB");
print("done: firstVar  = $firstVar\n");
print("done: secondVar = $secondVar\n\n");

sub firstSub{
    local ($firstVar) = $_[0];
    my($secondVar)    = $_[1];

    print("firstSub: firstVar  = $firstVar\n");
    print("firstSub: secondVar = $secondVar\n\n");

    secondSub();

    print("firstSub: firstVar  = $firstVar\n");
    print("firstSub: secondVar = $secondVar\n\n");
}

sub secondSub{
    print("secondSub: firstVar  = $firstVar\n");
    print("secondSub: secondVar = $secondVar\n\n");

    $firstVar  = "CCCCC";
    $secondVar = "DDDDD";

    print("secondSub: firstVar  = $firstVar\n");
    print("secondSub: secondVar = $secondVar\n\n");
}

This program prints:

firstSub: firstVar = AAAAA
firstSub: secondVar = BBBBB

secondSub: firstVar  = AAAAA
Use of uninitialized value at test.pl line 19.
secondSub: secondVar =

secondSub: firstVar  = CCCCC
secondSub: secondVar = DDDDD

firstSub: firstVar  = CCCCC
firstSub: secondVar = BBBBB

Use of uninitialized value at test.pl line 3.
done: firstVar  =
done: secondVar = DDDDD

 

 

#7

 
firstSub((0..10), "AAAA");

sub firstSub{
    local(@array, $firstVar) = @_;

    print("firstSub: array    = @array\n");
    print("firstSub: firstVar = $firstVar\n");
}

This program prints:

firstSub: array    = 0 1 2 3 4 5 6 7 8 9 10 AAAA
Use of uninitialized value at test.pl line 8.
firstSub: firstVar =

 

#8

 
firstSub("AAAA", (0..10));

sub firstSub{
    local($firstVar, @array) = @_;

    print("firstSub: array    = @array\n");
    print("firstSub: firstVar = $firstVar\n");
}
This program prints:
firstSub: array    = 0 1 2 3 4 5 6 7 8 9 10
firstSub: firstVar = AAAA

 

 

#9  Array 관련 함수

Function Description
defined(VARIABLE) returns true if VARIABLE has a real value and false if the variable has not yet been assigned a value. This is not limited to arrays, any data type can be checked. Also see the exists function for information about associative array keys.
delete(KEY) Removes the key-value pair from the given associative array. If you delete a value from the %ENV array the environment of the current process is changed, not that of the parent.
each(ASSOC_ARRAY) Returns a two-element list that contains a key and value pair from the given associative array. The function is mainly used so that you can iterate over the associate array elements. A null list is returned when the last element has been read.
exists(KEY) Returns true if the KEY is part of the specified associative array. For instance, exists($array{"Orange"}) returns true if the %array associative array has a key with the value of "Orange."
join(STRING, ARRAY) Returns a string that consists of all of the elements of ARRAY joined together by STRING. For instance, join(">>", ("AA", "BB", "CC")) returns "AA>>BB>>CC".
keys(ASSOC_ARRAY) Returns a list that holds all of the keys in a given associative array. The list is not in any particular order.
map(EXPRESSION, ARRAY) Evaluates EXPRESSION for every element of ARRAY. The special variable $_ is assigned each element of ARRAY immediately before EXPRESSION is evaluated.
pack(STRING, ARRAY) Creates a binary structure, using STRING as a guide, of the elements of ARRAY. You can look in Chapter 8, "References," for more information.
pop(ARRAY) Returns the last value of an array. It also reduces the size of the array by one.
push(ARRAY1, ARRAY2) Appends the contents of ARRAY2 to ARRAY1. This increases the size of ARRAY1 as needed.
reverse(ARRAY) Reverses the elements of a given array when used in an array context. When used in a scalar context, the array is converted to a string, and the string is reversed.
scalar(ARRAY) Evaluates the array in a scalar context and returns the number of elements in the array.
shift(ARRAY) Returns the first value of an array. It also reduces the size of the array by one.
sort(ARRAY) Returns a list containing the elements of ARRAY in sorted order. See Chapter 8, "References," for more information.
splice(ARRAY1, OFFSET, LENGTH, ARRAY2) Replaces elements of ARRAY1 with elements in ARRAY2. It returns a list holding any elements that were removed. Remember that the $[ variable may change the base array subscript when determining the OFFSET value.
split(PATTERN, STRING, LIMIT) Breaks up a string based on some delimiter. In an array context, it returns a list of the things that were found. In a scalar context, it returns the number of things found.
undef(VARIABLE) Slways returns the undefined value. In addition, it undefines VARIABLE which must be a scalar, an entire array or a subroutine name.
unpack(STRING, ARRAY) Does the opposite of pack().
unshift(ARRAY1, ARRAY2) Adds the elements of ARRAY2 to the front of ARRAY1. Note that the added elements retain their original order. The size of the new ARRAY1 is returned.
values(ASSOC_ARRAY) Returns a list that holds all of the values in a given associative array. The list is not in any particular order.

 

 

#10 출력하기

 
%array = ( "100", "Green", "200", "Orange");

while (($key, $value) = each(%array)) {
    print("$key = $value\n");
}
This program prints:
100 = Green
200 = Orange

 

 

#11

 

 

 

 
createPair("100",  "Kathy Jones");
createPair("200",  "Grace Kelly");
createPair("100", "George Orwell");

while (($key, $value) = each %array) {
    print("$key, $value\n");
};

sub createPair{
    my($key, $value) = @_;

    $array{$key} = $value;
};
This program prints
100, George Orwell
200, Grace Kelly

 

#12

 
createPair("100",  "Kathy Jones");
createPair("200",  "Grace Kelly");
createPair("100", "George Orwell");

while (($key, $value) = each %array) {
    print("$key, $value\n");
};

sub createPair{
    my($key, $value) = @_;

    while (defined($array{$key})) {
        $key++;
    }

    $array{$key} = $value;
};
This program prints:
100, Kathy Jones
101, George Orwell
200, Grace Kelly

 

 

 

'perl' 카테고리의 다른 글

Array 쪽 팁  (0) 2008.06.07
Array 다루기 #2  (0) 2008.06.05
Array 다루기 #1  (0) 2008.06.05
Passing Parameters to Functions  (0) 2008.06.05
Perl의 String 관련 함수  (0) 2008.03.22
bash는 float 변수 연산이 안된다.  (0) 2007.10.21
Posted by 김용환 '김용환'

댓글을 달아 주세요