replace data interactively..

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
I usually write code in Awk and new to perl. I could not get a code
for the following problem in awk.

I have a data file like this..


Here first four charaters and uniq id. i want to replace the
character  substr($0,17,2) and substr($0,19,3) with user
input....interactively using awk. How to read the file the replace
data interactively.
These characters represent a user id(17,2) and department code(19,3).
I want the awk should ask the user like this...


enter uniq id: V123
then it should go to that record and proceed like this...(it is better
to display the
record fields)
enter user id :
read id
enter dept code:
read deptcd

then replace the (17,2) character with id and (19,3) with deptcd when
it is finished reading the user input. I also want old values to be
displayed. If i need to change the value i will change, otherwise i
just press enter, so the old values will not be erased.

Thank you in advance...

Re: replace data interactively..

In article

Quoted text here. Click to load it

Use open to open the file:

  open(my $fh, '<', 'data.file') or die("Can't open data.file: $!");

Use the read line operator to read a line:

  while( my $line = <$fh> ) {

Remove the end-of-line character:


Unpack the fixed-length fields:

    my( $id, $fill, $c17, $c19, $rest ) = unpack("A4A13A2A3A*",$line);

Store the data in a hash:

    $data = [ $fill, $c17, $c19, $rest ];

Request ID from user:

  print "Enter unique ID: ";
  my $ans = <STDIN>;

Look up the record:

  if( exists $data ) {

Query for new data:

    print "Enter Dept code: ";
    my $deptcd = <STDIN>;

Substitute columns 17-18 and 19-21 with result:

    $data->[1] = substr($deptcd,0,2);
    $data->[2] = substr($deptcd,0,3);

Open an output file:

  open(my $oh, '>', '') or die("Can't open $!");

Write out result:
  for my $id ( sort keys %data ) {
    my $line = pack("A4A13A2A3A*",$id,@});
    print $oh "$line\n";

(None of the above has been tested).

Note that if the order of the records in the file is important, then
you will need to add code to maintain the order, for example by storing
the user ids in a separate array, adding a sequence number to the
record, or following the advice in 'perldoc -q order' "How can I make
my hash remember the order I put elements into it?"

Note that your question doesn't seem to have anything to do with Perl
modules, so I recommend you post any additional questions to

Jim Gibson

Re: replace data interactively..

Quoted text here. Click to load it

thank you ... but it is giving compilation curly bracket

Re: replace data interactively..

In article

Quoted text here. Click to load it

I was not attempting to provide you with a complete, working program.
You will have to supply the missing pieces yourself, one of which is
the rest of the if statement.

Good luck.

Jim Gibson

Site Timeline