[완료] perl 간단한 질문입니다.

freemckang의 이미지

차일피일 미루다가 "Perl이 보이는 그림책"을 구매하여 perl공부를 시작하게 되었습니다. 그런데 예제를 돌리다가 질문이 있어서 이렇게 글을 씁니다.

@a = ();
print "Element num : " . $#a + 1 . "\n";

전 이것의 결과가 "Element num : 0"이 될줄 알았는데 "1"이 나오더군요.

@a = ();
print "Element num : ";
print $#a + 1 . "\n";

이것의 결과는 예측했던대로 "Element num : 0"입니다.

kubuntu feisty 사용중이고요, perl 버전은 5.8.8입니다.

cjh의 이미지

perlop 문서를 보시면 + - . 은 연산순위가 동일하고 left associated 로 나옵니다.

그러면 위 문장은

"Element num : " . $#a + 1 . "\n" -> ( ( ("Element num : " . $#a) + 1 ) . "\n" )

으로 해석이 되겠지요. 그러면 답이 1이 나오게 됩니다.

("Element num : " . $#a) + 1
= "Element num : -1" + 1
= 0 + 1
= 1

이렇게 됩니다. "Element num : -1"이 0이 되는 이유는

int("Element num : -1")

의 값을 보시면 알 수 있겠지요.

원하시는 결과를 얻으려면 다음과 같이 하는 것이 안전합니다.

print "Element num : " . ($#a + 1) . "\n";
print "Element num : " , $#a + 1 , "\n";
printf "Element num : %d\n", $#a + 1;

--
익스펙토 페트로눔

--
익스펙토 페트로눔

freemckang의 이미지

명확한 댓글에 감사드립니다 (--)(__)

句日新, 日新 日新 又日新.

句日新, 日新 日新 又日新.

aero의 이미지

Perl에서 array의 요소 갯수를 알아내려면
$#배열명 이 해당 배열의 최대 index count를 넘겨주기 때문에
$#배열명+1 하면 배열내의 요소 갯수가 되지만
가독성이 떨어지고 side effect의 가능성이 위의 경우처럼 존재하므로

단순히 배열내의 요소 갯수를 얻으려면
scalar(@배열명) 으로 명시적으로 작성하시는게 가독성에서 더 낫습니다.

그리고 Perl이 보이는 그림책은 서점에서 얼핏 봤는데
나온지 좀 지난 일본책을 번역해서 그런지
최신 Perl경향과 맞지 않는 부분도 좀 있어보이더군요.

freemckang의 이미지

예전에 봤던 "Perl은 과연 죽었는가? (http://kldp.org/node/74080)" 를 즐겨찾기에 추가해놓으면서 짬짬이 보고 있지만, 역시나 perl에 대한 '가장' 기본적인 지식도 없는 터라... 일단은 제일 쉬운 책으로 시작하게 되었습니다 :-) 좀더 열심히 공부해서 위에 링크 걸린 쓰레드를 의미있게 즐길 수 있는 날이 어서 오기를... :)

句日新, 日新 日新 又日新.

句日新, 日新 日新 又日新.

jg의 이미지

Quote:
scalar(@배열명) 으로 명시적으로 작성하시는게 가독성에서 더 낫습니다.

급할 때는 +@{배열명} 과 같이 써도 되겠군요.
3 + +@{배열명} 같은 경우에는 그냥 3 + @{배열명} 을 써야하지만요.
0+@{배열명} 을 쓰시는 분도 계실지 모르겠습니다.

size(@{배열명}) 과 같이 size같은 키워드를 추가해줘도 되지 않을까 싶은데 말이죠..

--
perl -e's@@JEON Myoung-jin@;sub man{s| _|her e|}
sub see{s;^;Just;;u;s;e ;Perl ;;to;print$_,$/}$uperMan=M;
s=^....=U are not=;s~$uperMan~~;&admitIt;s=U are = A=;s|young|_|;&man;
sub admitIt{say;ye;s!-\w+! Hacker!};see U'

$Myoungjin_JEON=@@=qw^rekcaH lreP rehtonA tsuJ^;$|++;{$i=$like=pop@@;unshift@@,$i;$~=18-length$i;print"\r[","~"x abs,(scalar reverse$i),"~"x($~-abs),"]"and select$good,$day,$mate,1/$~for 0..$~,-$~+1..-1;redo}

freemckang의 이미지

서명 부분을 보니, "누워서 읽는 알고리즘"에 나온 3줄짜리 perl code (전혀 이해 못함 ;;)가 생각이 나네요.. ^^;;

句日新, 日新 日新 又日新.

句日新, 日新 日新 又日新.

jg의 이미지

제가 짠 코드라 전 알아보지만 저도 남이 짠 걸 보려면 시간이 엄청 오래걸려요.
저런 코드는 그냥 장난으로 받아주세요. ^^;

--
생각해보니

"size"+@{배열명} 이렇게 쓸수도 있겠네요. (남이 알아볼라나;;)

--
perl -e's@@JEON Myoung-jin@;sub man{s| _|her e|}
sub see{s;^;Just;;u;s;e ;Perl ;;to;print$_,$/}$uperMan=M;
s=^....=U are not=;s~$uperMan~~;&admitIt;s=U are = A=;s|young|_|;&man;
sub admitIt{say;ye;s!-\w+! Hacker!};see U'

$Myoungjin_JEON=@@=qw^rekcaH lreP rehtonA tsuJ^;$|++;{$i=$like=pop@@;unshift@@,$i;$~=18-length$i;print"\r[","~"x abs,(scalar reverse$i),"~"x($~-abs),"]"and select$good,$day,$mate,1/$~for 0..$~,-$~+1..-1;redo}

aero의 이미지

Perl 6에서는 이렇게 바뀝니다.

Number of elements in an array:

Was: $#array+1 or scalar(@array)
Now: @array.elems

Index of last element in an array:

Was: $#array
Now: @array.end

Therefore, last element in an array:

Was: $array[$#array]
Now: @array[@array.end]
@array[-1] # also works

cjh의 이미지

Was: $#array
Now: @array.end

음... 그래도 perl5는 $ 로 시작하면 무조건 scalar (물론 ref 빼고)라고 알 수 있었지만
@array.end 가 scalar라면 메소드를 모르면 scalar인지 array인지 알 수 없어서
코드 읽기가 더 어려워지는건 아닌지 모르겠군요.

--
익스펙토 페트로눔

--
익스펙토 페트로눔

jg의 이미지

배열을 마치 객체처럼 보는 것이군요.
저런식의 코드가 가능하다면 실제 객체에서도 기존의 -> 의 호출에서 . 호출로 바뀔 수 있을 것 같네요.
$obj->call 에서 @obj.call 로 말이죠. ( 실제로는 잘 모르겠지만;; )

@source = (1, 2, 3);
@dest = @source[ 1, 2 ];

이런 코드는 여전히 유효하겠죠?

--
perl -e's@@JEON Myoung-jin@;sub man{s| _|her e|}
sub see{s;^;Just;;u;s;e ;Perl ;;to;print$_,$/}$uperMan=M;
s=^....=U are not=;s~$uperMan~~;&admitIt;s=U are = A=;s|young|_|;&man;
sub admitIt{say;ye;s!-\w+! Hacker!};see U'

$Myoungjin_JEON=@@=qw^rekcaH lreP rehtonA tsuJ^;$|++;{$i=$like=pop@@;unshift@@,$i;$~=18-length$i;print"\r[","~"x abs,(scalar reverse$i),"~"x($~-abs),"]"and select$good,$day,$mate,1/$~for 0..$~,-$~+1..-1;redo}

aero의 이미지

저런식의 코드가 가능하다면 실제 객체에서도 기존의 -> 의 호출에서 . 호출로 바뀔 수 있을 것 같네요.
$obj->call 에서 @obj.call 로 말이죠. ( 실제로는 잘 모르겠지만;; )

네 그렇게 바뀝니다.

@source = (1, 2, 3);
@dest = @source[ 1, 2 ];
이런 코드는 여전히 유효하겠죠?

참고
Perl6::Perl5::Differences
http://moritz.faui2k3.org/pugs/docs/Perl6/Perl5/Differences.pod.html

Everyday Perl 6
http://www.perl.com/pub/a/2007/05/10/everyday-perl-6.html

Introduction to Perl6
http://www.szabgab.com/talks/perl6/

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.