2012-10-19 3 views
2

저는 Perl에 익숙하지 않아 의존하고있는 프로젝트를 완료해야합니다. 폴더에있는 사진을 찍고 DB에서 이름을 조회 한 다음 해당 행의 다른 값을 기반으로 그림의 이름을 바꿔야합니다.DB의 값을 기준으로 파일 이름 바꾸기

그래서 내가 다음 USERID에서

010300000000001002 

에 대한 DB에서 스크립트 모양을 가질 필요가 사진

010300000000001002.jpg 

에게 이름을 바꿀 필요가 말한다. 그런 다음 일치 항목을 찾으면 동일한 행에서 EMPNUM 값을 찾아야합니다. 그리고 그래서 최종 제품은 다음과 같이 끝날 것 EMPNUM 값을이 경우에 (1002)와 같 value.jpg에 사진을 이름을 변경 :

Old Picture: 010300000000001002.jpg 
New Picture: 1002.jpg 

그런 다음 해당 폴더에있는 모든 사진에 대해 반복합니다.

DB를 스크립트에서 읽기

:

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

use DBI; 
# Replace datasource_name with the name of your data source. AdventureWorksDW \dbo.DimEmployee 
# Replace database_username and database_password 
# with the SQL Server database username and password. 
my $data_source = q/not giving the data source/; 
my $user = q/Not giving the user/; 
my $password = q/Not Giving the password /; 
my $dbh = DBI->connect($data_source, $user, $password) 
    or die "Can't connect to $data_source: $DBI::errstr"; 

# Catch and display status messages with this error handler. 
sub err_handler { 
    my ($sqlstate, $msg, $nativeerr) = @_; 
    # Strip out all of the driver ID stuff 
    $msg =~ s/^(\[[\w\s:]*\])+//; 
    print $msg; 
    print "===> state: $sqlstate msg: $msg nativeerr: $nativeerr\n"; 
    return 0; 
} 

$dbh->{odbc_err_handler} = \&err_handler; 

$dbh->{odbc_exec_direct} = 1; 

# Prepare your sql statement (perldoc DBI for much more info). 
my $sth = $dbh->prepare('select userid, empnum from dbo.emp0'); 

# Execute the statement. 
if ($sth->execute) 
{ 
    # This will keep returning until you run out of rows. 
    while (my $row = $sth->fetchrow_hashref) 
    { 
     print "ID = $row->{userid}, Name = $row->{empnum}\n"; 
    } 
} 

$dbh->disconnect; 

복사 및 이름 변경 파일 스크립트 :

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

my $i = 1; 
my @old_names = glob "/root/pics/*.jpg"; 


foreach my $old_name (@old_names) { 

    my $new_name = "picture$i" . ".jpg"; 

    rename($old_name, "/root/pics/$new_name") or die "Couldn't rename $old_name to $new_name: $!\n"; 

} continue { $i++ } 

print "Pictures have been renamed.\n"; 

편집 : 이것은 내가 함께 결국 무엇이며 작업을 수행합니다.

#!/usr/bin/perl -w 
use strict; 
use File::Copy; 
use DBI; 

my $data_source = q/db/; 
my $user = q/user/; 
my $password = q/password/; 
my $dbh = DBI->connect($data_source, $user, $password) 
    or die "Can't connect to $data_source: $DBI::errstr"; 

# Catch and display status messages with this error handler. 
sub err_handler { 
    my ($sqlstate, $msg, $nativeerr) = @_; 
    # Strip out all of the driver ID stuff 
    $msg =~ s/^(\[[\w\s:]*\])+//; 
    print $msg; 
    print "===> state: $sqlstate msg: $msg nativeerr: $nativeerr\n"; 
    return 0; 
} 
$dbh->{odbc_err_handler} = \&err_handler; 
$dbh->{odbc_exec_direct} = 1; 

sub move_image 
{ 
    my $user_id = $_[0]; 
    my $emp_num = $_[1]; 

    my $old_name = "/root/picS/${user_id}.jpg"; 

    my $new_name = "/root/picD/${emp_num}.jpg"; 

    move($old_name, $new_name) or return 0; 

    return 1; 
} 

# Prepare your sql statement (perldoc DBI for much more info). 
my $sth = $dbh->prepare('select userid, empnum from dbo.emp0'); 

# Execute the statement. 
if ($sth->execute) 
{ 
    # This will keep returning until you run out of rows. 
    while (my $row = $sth->fetchrow_hashref) 
    { 
     my $user_id = $row->{userid}; 
     my $emp_num = $row->{empnum}; 

     if (move_image($user_id, $emp_num)) 
     { 
      print "Moved image $user_id to $emp_num successfully\n"; 
     } 
     else 
     { 
      print "Could not move image $user_id to $emp_num successfully\n"; 
     } 
    } 
} 

$dbh->disconnect; 
+0

필자가 예를 든 것은 나쁜 예입니다. EMPNUM은 USERID 값의 끝에 있습니다. 변경할 필요가있는 사진의 90 %는 그렇지 않습니다. – almyz125

+0

글쎄 지금까지 몇 가지 스크립트가 있는데 첫 번째 스크립트는 DB에 연결하여 연결을 테스트합니다. 두 번째는 DB에 연결하고 필요한 값을 표시합니다. 세 번째는 반복적으로 그림을 테스트 이름으로 바꿉니다. 내가 말했듯이 나는 Perl에 완전히 새로운 것이다. 이 스크립트를 사용하여 스크립트의 여러 부분을 시험해 보았습니다. 나는 DB에 연결하고 읽고, 그림의 이름을 바꾸는 방법을 배우고 싶었다. 나는이 모든 것을 지금 하나로 묶으려고 노력하고 있다고 생각한다. – almyz125

+0

내 목표를 달성하기 위해 이들을 함께 스크립트로 가져 오려면 어떻게해야합니까? – almyz125

답변

2

첫째을, 나는 File::Copy에서 move을 사용하는 것이 좋습니다 것입니다. rename subroutine에는 사용시기가 제한되어 있습니다. 그러나 두 이미지가 항상 같은 폴더에있을 것이라는 확신이 있다면 rename이 좋으며 더 효율적일 수도 있습니다.

File::Copy를 사용 할 수 있도록 코드의 상단에 다음을 추가합니다

use File::Copy; 

둘째, 당신은 여기에 기능을 통합하려는 경우, 나는 서브 루틴에 "이동"코드를 만들 것입니다.

sub move_image 
{ 
    my $user_id = $_[0]; 
    my $emp_num = $_[1]; 

    my $old_name = "/root/pics/${user_id}.jpg"; 

    my $new_name = "/root/pics/picture${emp_num}.jpg"; 

    move($old_name, $new_name) or return 0; 

    return 1; 
} 

그런 다음 서브 루틴을 호출 : 내가 보였다 같은

# This will keep returning until you run out of rows. 
while (my $row = $sth->fetchrow_hashref) 
{ 
    my $user_id = $row->{userid}; 
    my $emp_num = $row->{empnum}; 

    if (move_image($user_id, $emp_num)) 
    { 
     print "Moved image $user_id to $emp_num successfully\n"; 
    } 
    else 
    { 
     print "Could not move image $user_id to $emp_num successfully\n"; 
    } 
} 

그냥 원래 스크립트에 서브 루틴을 추가합니다. 두 개의 다른 스크립트를 사용하지 마십시오. Subroutines은 매우 유용합니다.

+0

감사합니다! Java에서 제공되는 서브 루틴은 메소드와 같습니다. 다시 한 번 감사드립니다! – almyz125

+1

내가 도울 수있어서 기뻐요!'Method'는 객체 지향 프로그래밍 (Object-Oriented Programming) 경향이있다. 그것은 단지 의미론 일 뿐이지 만 이것을 읽으려면 다음을 원할 수 있습니다. http://suite101.com/article/procedure-subroutine-or-function--a8208 –

+0

감사합니다. – almyz125